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

前端 未结 3 411
抹茶落季
抹茶落季 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: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
    });
    

提交回复
热议问题