ASP.NET Core 使用多种身份验证方法 [英] ASP.NET Core Using Multiple Authentication Methods

查看:43
本文介绍了ASP.NET Core 使用多种身份验证方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using both Cookie Authentication Middleware and JWT Authentication Middleware. When I sign in the user I create custom Claims and attach those to the cookie based identity. I also get a jwt token from an external source, and that has its own claims (I use this token to access external resources). My controller class looks something like this when enabling Authentication

[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;

根据上面的代码片段,如果 Cookie 或 JWT 身份验证成功,则请求被视为已通过身份验证.如果 Cookie Auth 或 JWT auth 失败,我的要求是拒绝该请求.对于我的情况,只使用一个模式不是一个好的选择.如果我的 cookie 有效但我的令牌已过期,我想以未通过身份验证"为由使请求失败.我该怎么做?

Based on the code snippet above, if either, Cookie or JWT auth is successful the request is deemed Authenticated. My requirement is to reject the request if either Cookie Auth or JWT auth fails. Using just one schema is not a good option for my case. If my cookie is valid but my token has expired I would like to fail the request on grounds of "not being authenticated". How can I do that?

推荐答案

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

Use policy based authentication. There you can check if current ClaimsPrincipal (context.User) has 2 Identities, 1 from each successfully passed authentication scheme. Configure policy

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;
        });
    });
});

为控制器指定授权策略

[Authorize(Policy = "RequireAllSchemes")]
public class MixedController : Controller

这篇关于ASP.NET Core 使用多种身份验证方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆