在用户中有两个声明身份(ClaimsPrincipal),仅一个用于[授权]

问题描述 投票:0回答:1

我有两个JWT包含在对我的服务的所有调用中。第一个(称为UserJwt)是我要用于大多数服务操作的[Authorize]的那个。第二个(称为ApplicationJwt)具有有用的信息,我也想将其包含在User.Identities对象的ClaimsIdentity列表中。

我设置了代码,以便始终使用UserJwt并忽略ApplicationJwt

services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        // Setup the JWT stuff here for the UserJwt         
    })

这很好,但是我希望两个JWT都被解析并放入User.Identities列表。

我尝试设置代码以遵循此answer,(问题是:Use multiple JWT Bearer Authentication),但这允许任一个UserJwtApplicationJwt)。

最糟糕的是,我需要同时要求两者。但是,我更喜欢它仅要求UserJwt,但是如果发现ApplicationJwt,则将其包括在内。

ClaimsIdentity

如何将两个JWT都包含在 services.AddAuthentication() .AddJwtBearer("UserJwt", options => { // Setup the JWT stuff here for the UserJwt }) .AddJwtBearer("ApplicationJwt", options => { // Setup the JWT stuff here for the ApplicationJwt }); services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .AddAuthenticationSchemes("UserJwt", "ApplicationJwt") .Build(); }); 列表中,让UserJwt成为用于User.Identities的JWT,还要在某些服务操作上允许[Authorize]

c# security asp.net-core jwt asp.net-core-3.1
1个回答
0
投票

这里的一个选项是默认策略为[Authorize(Policy = "ApplicationJwt")]

假设UserJwt包含特定声明:

adding custom requirements

请注意,当不满足要求时,用户仍将通过身份验证,但被拒绝访问。要处理禁止的情况,请使用options.DefaultPolicy = new AuthorizationPolicyBuilder() .AddAuthenticationSchemes("ApplicationJwt", "UserJwt") .RequireAuthenticatedUser() .AddRequirements( // Assume UserJwt contains a AuthenticationMethod claim whose value is equal to User new ClaimsAuthorizationRequirement( ClaimTypes.AuthenticationMethod, new[] { "User" } ) ) .Build(); 事件:

JwtBearerEvents.OnForbidden
© www.soinside.com 2019 - 2024. All rights reserved.