Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 738
penartur Avatar asked Jun 16 '17 10:06

penartur


People also ask

Does Azure function support managed identity?

With a managed identity from Azure Active Directory (AAD) allows Azure Function App to access other AAD protected resources such as Key Vault. You can assign a system-assigned identity tied to your Function App. In the Azure Portal through platform features click Identity and switch System assigned to On.

How do you authenticate with Azure function?

That token needs to be passed in the Authorization header (usually known as the Bearer token) Create an Azure Function App. Make your Function auth anonymous. Then use Jwt security packages to read the token and authenticate/authorize the user using the token.


1 Answers

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.
 }
like image 64
Kzrystof Avatar answered Oct 17 '22 04:10

Kzrystof