用户使用身份验证方案的策略中缺少身份

时间:2020-06-09 12:28:09

标签: c# asp.net-core authentication asp.net-identity claims-based-identity

我已经创建了一个使用两种身份验证类型的ASP.NET Core 3.1应用程序-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会以某种方式隐藏使用相同身份验证类型创建的用户身份?

1 个答案:

答案 0 :(得分:2)

授权中间件将评估您的策略并运行将覆盖用户的身份验证逻辑。上下文

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

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,并且如果您注释该行,则身份验证逻辑将不会运行,您的自定义用户对象将在那里