用户在具有身份验证方案的策略中缺少身份

User is missing identities in policy with authentication scheme

我创建了一个 ASP.NET 核心 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 会以某种方式隐藏使用相同身份验证类型创建的用户身份?

授权中间件将评估您的策略并运行验证逻辑将覆盖user.Context

这是相关的代码片段(我删除并简化了代码以突出显示相关部分):

public virtual async Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy policy, HttpContext context)
{
    if (policy.AuthenticationSchemes != null && policy.AuthenticationSchemes.Count > 0)
    {
        var newPrincipal = await context.AuthenticateAsync(scheme).Principal;

        if (newPrincipal != null)
        {
            context.User = newPrincipal;
            return AuthenticateResult.Success(new AuthenticationTicket(newPrincipal, string.Join(";", policy.AuthenticationSchemes)));
        }
        else
        {
            context.User = new ClaimsPrincipal(new ClaimsIdentity());
            return AuthenticateResult.NoResult();
        }
    }
    ...
}

因此,如您所见,当您为策略定义方案时,您输入 "if" 语句(这将设​​置一个新的 context.User,如果您注释该行,身份验证逻辑不会 运行 而您的自定义用户对象将在那里