简体   繁体   中英

DotNet Core Api - Different Authentication for specific endpoints

I have a tricky scenario - I have a Dotnet Core web api that uses Jwt bearer token for auth. We have a use case that we would like to generate a slightly different bearer token for a subset of endpoints - this bearer token has different claims than the main token. I am able to generate the new token and claims - its is Authenticated to the system and works, BUT I dont want it to work on ALL endpoints.

It would need to be something like:
bearer_token1 => can access all endpoints and work (this is our current bearer token)
bearer_token2 => can access SOME endpoints BUT NOT ALL (this is our new token)

endpoint1 needs to work ONLY with bearer_token1.If a user tries to use bearer_token2, they would get a 401 error
endpoint2 needs to work bearer_token1 OR bearer_token2.

I can obviously add code to each endpoint to look at the claims and fail bearer_token2 where needed, but we have a lot of endpoints.

Is there a way to specify that a controller needs to authorize with a specific token?

Does this make sense?

If you have multiple authentication schemes for different bear token, you could use Authorize attribute to set the AuthenticationSchemes.

You could set the Authorize AuthenticationScheme for specific controller based on your opinion. Like below:

[Authorize(AuthenticationSchemes = 
    JwtBearerDefaults.AuthenticationScheme)]

You can specify any number of different policies, with any set of requirements.

The default policy only checks that the user is authenticated. You can replace the default policy to specify some other requirement that you can meet during your normal login process. With some other policy for your new login tokens. For example;

services.AddAuthorization(o =>
{
    var builder = new AuthorizationPolicyBuilder();
    builder.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
    builder.RequireAuthenticatedUser();
    builder.RequireClaim(ClaimTypes.Role, "all_access");
    o.DefaultPolicy = builder.Build();

    o.AddPolicy("OtherPolicy", b => {
        b.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
        b.RequireAuthenticatedUser();
        b.RequireClaim(ClaimTypes.Role, "some_access");
    });
}

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