C#C
C#3y ago
S-IERRA

❔ ASP.NET always validates invalid JWT

I have a custom configuration for Asp.net where the JWT Token is stored in an http-only cookie, because of this there is 1 method in specific that is always returning 200 no matter if there is no actual JWT attached

    public static void RegisterAuthorization(this IServiceCollection serviceCollection, IConfiguration configuration)
    {
        var jwtConfig = configuration.GetSection("Jwt").Get<JwtConfig>()!;
        serviceCollection.Configure<JwtConfig>(configuration.GetSection("Jwt"));

        serviceCollection.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {   
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidAudience = jwtConfig.Audience,
                    ValidIssuer = jwtConfig.Issuer,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Key))
                };
                
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        context.Token = context.Request.Cookies["JwtToken"];

                        return Task.CompletedTask;
                    }
                };
            });
    
        serviceCollection.AddAuthorization(options =>
        {
            options.AddPolicy(NumixAuthPolicy.Admin.ToString(), policy => 
                policy.RequireClaim(ClaimTypes.Role, NumixRole.Administrator.ToString()));
        });
    
        serviceCollection.AddScoped(typeof(IAuthenticatorService), typeof(Authenticate));
    }
Was this page helpful?