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

99封情书 提交于 2020-01-01 02:34:10

问题


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?


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/35586663/how-to-apply-custom-validation-to-jwt-token-on-each-request-for-asp-net-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!