How to apply custom validation to JWT token on each request for ASP.NET WebApi?

前端 未结 3 412
抹茶落季
抹茶落季 2021-02-04 07:43

Is it possible to add custom validation to each request when authenticating web api calls using a bearer token?

I\'m using the following configuration and the applicatio

3条回答
  •  -上瘾入骨i
    2021-02-04 08:28

    on .Net Core you can add this to the JwtBearerOptions:

    options.Events = new JwtBearerEvents
    {
        OnTokenValidated = AdditionalValidation
    };
    

    Where your Validation function could look like this:

    private static Task AdditionalValidation(TokenValidatedContext context)
    {
        if ( /* any validation */ ) 
        {
            context.Fail("Failed additional validation");
        }
    
        return Task.CompletedTask;
    }
    

    The good news is that context will include all you need, the JWT Token, the HttpContext, the ClaimsPrincipal, etc.

提交回复
热议问题