How to get current user identity in Azure Function with Azure Authentication?

penartur picture penartur · Jun 16, 2017 · Viewed 15.4k times · Source

I have created a new Function App, enabled App Service Authentication / Authorization for it ("Use Authentication / Authorization to protect your application and work with per-user data") and disabled non-authenticated requests.

Everything seems to be working correctly so far. If I try to request my HttpTriggered function, it requires me to log in first; once I'm logged in, all requests are processed as they should be. So there is no problem with "protect your application" part.

However, I'm totally stuck with the "work with per-user data" part. My Azure Function is invoked as

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)

And there is nothing related to authentication in HttpRequestMessage. (AuthorizationLevel.Anonymous seems to control the entirely different thing - namely, if the function could be called by anyone or only by those who have a fixed API key).

How do I get the identity of authenticated user who called the function?

Answer

Kzrystof picture Kzrystof · Mar 18, 2019

Using the Azure Function runtime v2.0.12309, you can retrieve the authenticated user information from the ClaimsPrincipal instance injected in the Run method:

public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
    HttpRequest httpRequest, 
    ILogger logger, 
    ClaimsPrincipal claimsPrincipal)
 {
            // Explores the authenticated user's claims in claimsPrincipal.
 }