【发布时间】:2020-09-28 15:07:53
【问题描述】:
我创建了一个 ASP.NET Core 3.1 应用程序,它使用 2 种身份验证类型 - cookie 和 JWT 承载。
我已经设置了一个方案,可以根据请求的路径将用户重定向到正确的方案:
.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = "smart";
sharedOptions.DefaultChallengeScheme = "smart";
})
.AddPolicyScheme("smart", "Bearer Authorization or Cookie", options =>
{
options.ForwardDefaultSelector = context =>
{
var requestPath = context.Request.Path;
if (CookiePolicyPathRegex.IsMatch(requestPath))
{
return CookieAuthenticationDefaults.AuthenticationScheme;
}
return JwtBearerDefaults.AuthenticationScheme;
};
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOAuthServiceScheme(Configuration); // Custom handler for JWT
我这样设置授权策略:
options.AddPolicy(ApiPolicies.CookiePolicy, policy =>
{
// policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
policy.RequireRole(Roles.Access);
});
options.AddPolicy(ApiPolicies.JwtPolicy, policy =>
{
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
});
这很好,正在触发正确的策略,但我有一个问题。在我的集成测试中,我使用了一个为 cookie 身份验证添加 ClaimsIdentity 的中间件:
public async Task Invoke(HttpContext context)
{
// Removed for brevity
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
context.User = new ClaimsPrincipal(claimsIdentity);
await _next(context);
}
中间件设置为在 Auth 中间件之前运行
ConfigureAdditionalMiddleware(app);
app.UseAuthentication();
app.UseAuthorization();
如果我从 cookie 策略中取消注释 // policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme); 部分,则授权部分看不到在中间件中创建的身份。如果我留下评论,身份就在那里,包括声明、身份验证类型和所有内容。如果我查看转发到两个身份验证方案的 PolicyScheme,身份就在那里。
我的问题是,为什么添加 CookieAuthenticationDefaults.AuthenticationScheme 会以某种方式隐藏使用相同身份验证类型创建的用户身份?
【问题讨论】:
-
是否可以将中间件放在
UseAuthentication中间件之后,因此尚未设置身份? -
好点,我编辑了帖子以包含 Startup.cs 的那部分,但我认为它应该没问题。身份在转发到身份验证方案的方案中可见
-
身份可以在
UseAuthentication和UseAuthorization中设置,请参阅这篇文章以了解更多关于UseAuthentication究竟是什么stackoverflow.com/questions/48836688/…
标签: c# asp.net-core authentication asp.net-identity claims-based-identity