简体   繁体   中英

secure webapi with a valid JWT based on claims

Here is how I've created an claim based authorization attribute. But I have some doubts about how this work.

Given the code from my startup class:

public void Configuration(IAppBuilder app)
    {
        if (app == null)
        {
            throw new ArgumentNullException(nameof(app));
        }

        app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        {
            Authority = ConfigurationManager.AppSettings["Authentication:Authority"],
            RequiredScopes = ConfigurationManager.AppSettings["Authentication:Scopes"].Split(' ').ToList(),
            PreserveAccessToken = true
        });
    }

I was expecting that if I have this attribute to my controller and I send an invalid token(invalid signature) the request will be automatically rejected as unauthorized, but the code from the attribute is executed.

Shouldn't OWIN validate the token first?

How to make sure that the token is valid (valid stricture, signature, not expired, etc) and only after validate the claims?

The issue is within your linked question in your ClaimAuthorizationAttribute - it doesn't ever call base.IsAuthorized() , thus bypassing the built in protection mechanisms offered by AuthorizeAttribute .

Instead of just returning here after seeing whether or not the claim is present:

return token.Claims.Any(c => c.Type.Equals(this.Claim) && c.Value.Equals("True", StringComparison.OrdinalIgnoreCase));

You should instead carry on with making sure that the base class is satisfied, and thus the token itself is valid, too:

var claimValid = token.Claims.Any(c => c.Type.Equals(this.Claim) && c.Value.Equals("True", StringComparison.OrdinalIgnoreCase));
if (claimValid)
    return base.IsAuthorized();
else
    return false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM