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

前端 未结 3 410
抹茶落季
抹茶落季 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条回答
  • 2021-02-04 08:24

    The best way I would say is to write custom attribute. You need to inherit AuthorizeAttribute class and overridde AuthorizeCore method, there you can add custom validation.

    Once you are done, just decorate your controller or method with it.

    https://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute(v=vs.118).aspx

    Implementation example:

    public class MyCustomAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            // your validation here
        }
    }
    

    Usage examle:

    [MyCustom]
    public ActionResult MyAction()
    {
        return View();
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-04 08:42

    To add additional logic to authenticate or validate incoming tokens:

    1) Using an Authentication Provider

    1. Write a custom provider inherit from OAuthBearerAuthenticationProvider or implement IOAuthBearerAuthenticationProvider

    2. in your custom authentication provider, override/implement ValidateIdentity(...) and/or RequestToken(...) to check the incoming token with each request

    3. Use your custom provider by assigning it to the JwtBearerAuthenticationOptions.Provider property

    Example:

    app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
    {
        // ... other properties here
        Provider = new MyCustomTokenAuthenticationProvider()
        // ... other properties here
    });
    

    2) Using A Token Handler

    1. Write a custom token handler inherit from JwtSecurityTokenHandler

    2. override any relevant method you like to extend (there are many!)

    3. Use your custom token handler by assigning it to the JwtBearerAuthenticationOptions.TokenHandler property

    Example:

    app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
    {
        // ... other properties here
        TokenHandler = new MyCustomTokenHandler()
        // ... other properties here
    });
    
    0 讨论(0)
提交回复
热议问题