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
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:
Write a custom provider inherit from OAuthBearerAuthenticationProvider or implement IOAuthBearerAuthenticationProvider
in your custom authentication provider, override/implement ValidateIdentity(...)
and/or RequestToken(...)
to check the incoming token with each request
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
});
Write a custom token handler inherit from JwtSecurityTokenHandler
override any relevant method you like to extend (there are many!)
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
});