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 ?