Home > Enterprise >  Validate a JWT from another C# ASP.NET Core 3.1 API that consumes it
Validate a JWT from another C# ASP.NET Core 3.1 API that consumes it

Time:09-17

So I am getting a JWT from a web call that comes from Service A to secure Service B with the same token. Unfortunately it uses a third party library so I don't know the exact key it issues but I can see it's payload just fine. Is there a way I can make my service know the token is okay somehow? I tried this in Startup.ConfigureServices

services.AddAuthentication()
            .AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ")?.Last() ?? string.Empty;
                        if (!string.IsNullOrEmpty(accessToken))
                            context.Token = accessToken;

                        return Task.CompletedTask;
                    }
                };
            });

Now this gets the JWT I expect and in a test case let's say this: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0LmNvbSJ9.XzkQ9hQ0JyhQDpFZ00Ukc_5ickUmjxVUBvlMrcEeycw

enter image description here

There is nothing wrong here and the 'context.Token' is getting set, but when I do this:

[Authorize(AuthenticationSchemes = "Bearer")]
[Route("[controller]/[action]")]
public class JobsUpdateController : ControllerBase

I get a 401 no matter what when using the '[Authorize(AuthenticationSchemes="Bearer")]'. Is there anyway I can do a custom authorize? Else I was thinking of doing some long form of setting my own authentication method and maybe making a custom attribute. But I was hoping I could just get the startup working for this if I know the 'issuer' and several other keys in the payload of what I expect.

CodePudding user response:

You can configure JWT validation in options.TokenValidationParameters.

This is NOT secure, and you're basically allowing pretty much any token. But regardless, here it is:

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(
        options => {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true, // `iss` claim
                ValidIssuers = new []{"https://localhost:1234"},
                ValidateAudience = false, // `aud` claim
                ValidateLifetime = false, // `exp`, `nbf` claims
                ValidateIssuerSigningKey = false, // signature
                SignatureValidator = (token, parameters) => new JwtSecurityToken(token), // don't validate signature
            };
        });
  • Related