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

查看:104
本文介绍了使用多种身份验证方法的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身份验证或JWT身份验证失败,则拒绝该请求.对于我的情况,仅使用一个模式不是一个好的选择.如果我的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天全站免登陆