Search code examples
.net.net-coreclaims

How does User.Claims are added from JWT (access token) in .net core?


this might sound like a strange question but there is some kind of flow in our code that I can't figure out what is going on and need some help from the .net community

in our startup.cs we have the following code that adds the authentication:

public override void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication()
        .AddJwtBearer()
        .AddCookie("Cookie");
}   

When someone is calling the service (using rest API call) he must provide a valid AccessToken in the Authorization header.

Now, we have a Filter class that is checking that when accessing a given method in a controller the user has the correct claim this method needs

this is the filter class:

namespace Authorization
{
    public class ClaimRequirementFilter : IAuthorizationFilter
    {
        private readonly Claim _claim;

        public ClaimRequirementFilter(Claim claim)
        {
            _claim = claim;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {

            var hasClaim = context.HttpContext.User.Claims.Any(c =>
                                    string.Equals(c.Type, _claim.Type, StringComparison.OrdinalIgnoreCase)
                                    && string.Equals(c.Value, _claim.Value, StringComparison.OrdinalIgnoreCase));
            if (!hasClaim)
            {
                context.Result = new UnauthorizedResult();
            }
        }
    }
}

And the way we are using it is like this:

[HttpGet]
[ActionName("GetUsers")]
[ClaimRequirement("api_access", "users.read")]
public async Task<IActionResult> GetUsers()
{
    return Ok("Great success!");
}

Now, what I can't figure out is how HttpContext.User.Claims is getting the claims from the JWT token ? I read so many documentation and articles but I can't figure this out

if someone has any shred of data this would be a great help

Thanks


Solution

  • After some digging the answer was that the AddJwtBearer function performs authentication by extracting and validating a JWT token from the Authorization request header.

    So the User.Claims are being populated after a valid JWT validation from the Authorization header

    More info can be found here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.jwtbearerextensions.addjwtbearer?view=aspnetcore-6.0