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 application already validates the JWT tokens correctly.
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
AuthenticationType = "jwt",
TokenEndpointPath = new PathString("/api/token"),
AccessTokenFormat = new CustomJwtFormat(),
Provider = new CustomOAuthProvider(),
});
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AllowedAudiences = new[] { "all" },
IssuerSecurityTokenProviders = new[] { new SymmetricKeyIssuerSecurityTokenProvider(Config.JWT_Issuer, Config.JWT_Key) },,
});
Now, because tokens are set to never expire, I'd like to add an additional custom validation step to each request made with a bearer token, so I can validate some additional information per request and deny access if needed.
Where is the right place to add this validation for each request?
ValidateIssuer, validates that the iss claim inside the access token matches the issuer(authority) that the API trusts (Ie, your token service). Verifies that the issuer of the token is what this API expects. ValidateAudience, validates that the aud claim inside the access token matches the audience parameter.
Specify a secret key in the appsettings.Next, create a section in the appsettings. json file for the Issuer, Audience, and Key information. This information will be used later to generate a JSON Web Token. Note that you can give any name to this section you want; I'll use the name “Jwt” for convenience.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With