我有两个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),但这允许任一个(UserJwt
或ApplicationJwt
)。
最糟糕的是,我需要同时要求两者。但是,我更喜欢它仅要求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]
?
这里的一个选项是默认策略为[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