使用多个JWT承载身份验证 [英] Use multiple JWT Bearer Authentication

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

问题描述

是否可以在ASP.NET Core 2中支持多个JWT令牌发行者? 我想提供用于外部服务的API,并且需要使用两种JWT令牌来源-Firebase和自定义JWT令牌发行者.在ASP.NET核心中,我可以为Bearer身份验证方案设置JWT身份验证,但只能为一个授权设置:

Is it possible to support multiple JWT Token issuers in ASP.NET Core 2? I want to provide an API for external service and I need to use two sources of JWT tokens - Firebase and custom JWT token issuers. In ASP.NET core I can set the JWT authentication for Bearer auth scheme, but only for one Authority:

  services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://securetoken.google.com/my-firebase-project"
            options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = "my-firebase-project"
                    ValidateAudience = true,
                    ValidAudience = "my-firebase-project"
                    ValidateLifetime = true
                };
        }

我可以有多个发行人和受众,但不能设置多个授权机构.

I can have multiple issuers and audiences, but I can't set several Authorities.

推荐答案

您完全可以实现想要的目标:

You can totally achieve what you want:

services
    .AddAuthentication()
    .AddJwtBearer("Firebase", options =>
    {
        options.Authority = "https://securetoken.google.com/my-firebase-project"
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "my-firebase-project"
            ValidateAudience = true,
            ValidAudience = "my-firebase-project"
            ValidateLifetime = true
        };
    })
    .AddJwtBearer("Custom", options =>
    {
        // Configuration for your custom
        // JWT tokens here
    });

services
    .AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .AddAuthenticationSchemes("Firebase", "Custom")
            .Build();
    });

让我们看一下您的代码与该代码之间的区别.

Let's go through the differences between your code and that one.

如果设置默认身份验证方案,则在每个单个请求中,身份验证中间件将尝试运行与默认身份验证方案关联的身份验证处理程序.由于我们现在有两种可行的身份验证方案,因此运行其中一种是没有意义的.

If you set a default authentication scheme, then on every single request the authentication middleware will try to run the authentication handler associated with the default authentication scheme. Since we now have two opssible authentication schemes, there's no point in running one of them.

每个添加身份验证的AddXXX方法都有几个重载:

Every single AddXXX method to add an authentication has several overloads:

  • 一种使用与身份验证方法关联的默认身份验证方案的方式,您可以
  • One where the default authentication scheme associated with the authentication method is used, as you can see here for cookies authentication
  • One where you pass, in addition to the configuration of the options, the name of the authentication scheme, as on this overload

现在,由于您两次使用相同的身份验证方法,但是身份验证方案必须是唯一的,因此您需要使用第二个重载.

Now, because you use the same authentication method twice but authentication schemes must be unique, you need to use the second overload.

由于将不再自动验证请求,因此将[Authorize]属性置于某些操作上将导致请求被拒绝并发出HTTP 401.

Since the requests won't be authenticated automatically anymore, putting [Authorize] attributes on some actions will result in the requests being rejected and an HTTP 401 will be issued.

由于这不是我们想要的,因为我们希望给身份验证处理程序一个机会来验证请求,因此我们通过指示FirebaseCustom身份验证方案都应为尝试以验证请求.

Since that's not what we want because we want to give the authentication handlers a chance to authenticate the request, we change the default policy of the authorization system by indicating both the Firebase and Custom authentication schemes should be tried to authenticate the request.

这不会阻止您对某些操作施加更多限制; [Authorize]属性具有 属性,可让您覆盖哪些身份验证方案有效.

That doesn't prevent you from being more restrictive on some actions; the [Authorize] attribute has an AuthenticationSchemes property that allows you to override which authentication schemes are valid.

如果您有更复杂的方案,则可以使用基于策略的授权.我发现官方文档很棒.

If you have more complex scenarios, you can make use of policy-based authorization. I find the official documentation is great.

让我们想象一些操作仅适用于Firebase发行的JWT令牌,并且必须具有特定值的声明;你可以这样:

Let's imagine some actions are only available to JWT tokens issued by Firebase and must have a claim with a specific value; you could do it this way:

// Authentication code omitted for brevity

services
    .AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .AddAuthenticationSchemes("Firebase", "Custom")
            .Build();

        options.AddPolicy("FirebaseAdministrators", new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .AddAuthenticationSchemes("Firebase")
            .RequireClaim("role", "admin")
            .Build());
    });

然后您可以在某些操作上使用[Authorize(Policy = "FirebaseAdministrators")].

You could then use [Authorize(Policy = "FirebaseAdministrators")] on some actions.

这篇关于使用多个JWT承载身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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