Renato Sanhueza
Renato Sanhueza

Reputation: 564

Load JWT into User.Identity automatically (ASP.NET Core 3.1)

I am working on a project with micro-services's architecture. I have one API Rest that works as an API Gateway where I want to get the username from a JSON Web Token. It may be important to note that the authentication and authorization of the system are being dealt with on another part of the system (I just need to get the username).

So far I was able to get the username from the JWT using this extension of HttpContext:

public static class HttpContextExtensions
{
    private static JwtSecurityToken GetJwt(this HttpContext httpContext)
    {
        bool existeToken = httpContext.Request.Headers.TryGetValue("Authorization", out StringValues authorizationValue);
        if (!existeToken)
        {
            return null;
        }
        string encodedToken = authorizationValue.FirstOrDefault().Split(" ", 2)[1];
        return new JwtSecurityTokenHandler().ReadJwtToken(encodedToken);
    }
    public static string GetUsername(this HttpContext httpContext)
    {
        JwtSecurityToken jwt = httpContext.GetJwt();
        Claim usernameClaim = jwt.Claims.FirstOrDefault(c => c.Type == "preferred_username");
        return usernameClaim?.Value;
    }
}

And then I can get the username on the controller:

string username = HttpContext.GetUsername();

I was wondering if there is a more elegant way to do this on .Net Core 3.1. I tried to configure my project so I can get all the Claims loaded into User.Identity in my Controller's Action, but I failed miserably. All the documentation I found was about previous versions of .Net Core.

I think I may be doing something wrong on the Startup.cs. If anyone can point me to the right direction I would really appreciate it.

Upvotes: 3

Views: 1401

Answers (1)

Tiago Barroso
Tiago Barroso

Reputation: 387

I did an approach by filling the User on HttpContext in a middleware:

public class AuthMiddleware
{
    private readonly RequestDelegate _next;

    public AuthMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext context)
    {
        string authHeader = context.Request.Headers["Authorization"];

        if (authHeader != null)
        {
            
            var jwtEncodedString = authHeader.Substring(7);

            var token = new JwtSecurityToken(jwtEncodedString: jwtEncodedString);

            var identity = new ClaimsIdentity(token.Claims, "basic");
            context.User = new ClaimsPrincipal(identity);
        }

        return _next(context);
    }
}

Then on app setup;

public static IApplicationBuilder UseApiConfiguration(this IApplicationBuilder app, IWebHostEnvironment env)
{
     // add middleware reference
     app.UseMiddleware<AuthMiddleware>();
     
     return app;
}

Upvotes: 2

Related Questions