使用多种身份验证方法的 ASP.NET Core

Jon*_*han 4 security authentication cookies jwt asp.net-core

同时使用 Cookie 身份验证中间件和 JWT 身份验证中间件。当我登录用户时,我创建自定义声明并将它们附加到基于 cookie 的身份。我还从外部来源获得了一个 jwt 令牌,它有自己的声明(我使用这个令牌来访问外部资源)。启用身份验证时,我的控制器类看起来像这样

[Authorize(AuthenticationSchemes = AuthSchemes)]
public class MixedController : Controller
// Requires the following imports:
// using Microsoft.AspNetCore.Authentication.Cookies;
// using Microsoft.AspNetCore.Authentication.JwtBearer;
private const string AuthSchemes =
    CookieAuthenticationDefaults.AuthenticationScheme + "," +
    JwtBearerDefaults.AuthenticationScheme;
Run Code Online (Sandbox Code Playgroud)

根据上面的代码片段,如果 Cookie 或 JWT 身份验证成功,则该请求被视为已通过身份验证。如果 Cookie 身份验证或 JWT 身份验证失败,我的要求是拒绝请求。对于我的情况,仅使用一种模式不是一个好的选择。如果我的 cookie 有效但我的令牌已过期,我想以“未通过身份验证”为由拒绝请求。我怎样才能做到这一点?

Ale*_*der 6

使用基于策略的身份验证。在那里您可以检查当前ClaimsPrincipal( context.User) 是否有 2 Identities、 1 来自每个成功通过的身份验证方案。配置策略

services.AddAuthorization(options =>
{
    options.AddPolicy("RequireAllSchemes", policy =>
    {
        policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
        policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
        policy.RequireAuthenticatedUser();
        policy.RequireAssertion(context =>
        {
            return context.User.Identities.Count() == 2;
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

为控制器指定授权策略

[Authorize(Policy = "RequireAllSchemes")]
public class MixedController : Controller
Run Code Online (Sandbox Code Playgroud)