简体   繁体   中英

Azure Function 2.x - Get Current User's Claims

I have an Azure Function 2.x (Asp.net Core) and am authenticating with Azure AD. I'm trying to access the logged-in user's Claims after authentication. Previously using Azure Functions 1.x we would get the Claims using ClaimsPrincipal.Current , as seen in the code below:

using System.Net;
using System.Collections.Generic;
using System.Security.Claims; 
using Microsoft.IdentityModel.Clients.ActiveDirectory; 

public static HttpResponseMessage Run(HttpRequestMessage req, out object document, TraceWriter log)
{
    string name = ClaimsPrincipal.Current.FindFirst("name").Value; 

    log.Info($"name is {name}");

    return req.CreateResponse(HttpStatusCode.OK, "Done");
}   

Any guidance on how we access Claims in Azure Functions 2.x using .Net Core?

This feature is now supported in C# in Azure Functions 2.0. You can now add ClaimsPrincipal as a parameter to your HttpTrigger function's signature, or you can access it on the HttpRequest object via req.HttpContext.User .

Support should be coming soon to JavaScript, and eventually all languages should support this feature.

Let me just post a code example here, see where ClaimsPrincipal parameter is:

[FunctionName("MyFunctionName")]
public static HttpResponseMessage Run(
            [HttpTrigger(
                AuthorizationLevel.Anonymous,
                "get", "post",
                Route = "MyFunctionName")]HttpRequestMessage req, 
            ILogger log, 
            ClaimsPrincipal claimsPrincipal)
{
    // My function code here...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM