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

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();
}

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.


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
});