Mr.Gomer
Mr.Gomer

Reputation: 649

Validating JWT token and reading claims (ASP NET)

So I'm trying to validate a token in a ASP NET core project. In my startup.cs i got the following code.

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    //ValidateAudience = true,
                    //ValidAudience = Configuration["Jwt:Audience"],
                    RoleClaimType ="groups",
                    ValidateAudience = false, // `aud` claim
                    ValidateLifetime = false, // `exp`, `nbf` claims
                    ValidateIssuerSigningKey = false, // signature
                    SignatureValidator = (token, parameters) => new JwtSecurityToken(token)
                };

                options.Events.OnTokenValidated =  context =>
                {
                    if (context.SecurityToken is JwtSecurityToken accessToken)
                    {
                        Console.WriteLine("=====> TOKEN EXISTS <=====");
                        var roles = accessToken.Claims.Where(x => x.Type == "groups").Select(x => x.Value).ToList();
                        foreach (var r in roles)
                            Console.WriteLine(r);
                    }
                        return Task.CompletedTask;
                };

But every time I make a request from postman with a token it fails and the stacktrace gives the following output.

{"EventId":13,"LogLevel":"Error","Category":"Microsoft.AspNetCore.Server.Kestrel","Message":"Connection id \u00220HMH7MN2T2OMN\u0022, Request id \u00220HMH7MN2T2OMN:00000002\u0022: An unhandled exception was thrown by the application.","Exception":"System.NullReferenceException: Object reference not set to an instance of an object.    at AdministrationService.Server.Startup.\u003C\u003Ec.\u003CConfigureServices\u003Eb__4_0(JwtBearerOptions options) in /src/Aftermarket.Server.DbApi/Server/Startup.cs:line 61

Line 61 one is:

options.Events.OnTokenValidated =  context =>

meaning thenOnTokenValidated returns null.

Why is this happening ?

Upvotes: 1

Views: 1126

Answers (1)

Senbar
Senbar

Reputation: 41

According to docs

JwtBearerOptions.Events { get; set; }

The object provided by the application to process events raised by the bearer authentication handler. The application may implement the interface fully, or it may create an instance of JwtBearerEvents and assign delegates only to the events it wants to process.

So You have to create JwtBearerEvents object first

JwtBearerEvents events= new JwtBearerEvents();
events.OnTokenValidated = context =>
{
    (...)
};
options.Events= events;

Upvotes: 2

Related Questions