dasiths / NEasyAuthMiddleware

Azure App Service Authentication (EasyAuth) middleware for ASP.NET CORE with fully customizable components and support for local debugging
MIT License
14 stars 6 forks source link

access_token from the /.auth/me endpoint? #10

Closed amd64char closed 2 years ago

amd64char commented 2 years ago

Lets say I wanted to get the value of id_token or access_token from the /.auth/me endpoint Is there a way to map those fields to the HttpContext.User? or can that field be mapped with the use of the CustomClaimMapper?

dasiths commented 2 years ago

Yes you will need to do that for claims that are not currently mapped. Have a look at this example https://github.com/dasiths/NEasyAuthMiddleware/blob/master/NEasyAuthMiddleware/Mappers/StandardPrincipalClaimMapper.cs

amd64char commented 2 years ago

I was able to figure it out. Looking at the headers I saw the token I needed was being sent as X-MS-TOKEN-. By implementing IClaimMapper, I created and registered a CustomClaimMapper class. From there I was able to grab the token and add it to the claim list. Thank you for your help, and providing such cool middleware components!

public class CustomClaimMapper : IClaimMapper
{
    private readonly IOptions<EasyAuthOptions> _easyAuthOptions;
    private readonly IHttpContextAccessor _contextAccessor;

    public CustomClaimMapper(IOptions<EasyAuthOptions> easyAuthOptions, IHttpContextAccessor contextAccessor)
    {
        _easyAuthOptions = easyAuthOptions;
        _contextAccessor = contextAccessor;
    }

    public ClaimMapResult Map(IHeaderDictionary headers)
    {

        // try and map the header claims from a value in the header
        string sAccessToken = "";

        if(headers.ContainsKey("X-MS-TOKEN-OKTA-ACCESS-TOKEN"))
        {
            sAccessToken = headers["X-MS-TOKEN-OKTA-ACCESS-TOKEN"].First();
        }

        return ClaimMapResult.Success(new[]
        {
            new Claim(ClaimTypes.Webpage, _contextAccessor.HttpContext.Request.Path),
            new Claim("access_token", sAccessToken)
        });

    }
}