Dotnet core 2.0 身份验证多模式身份 cookie 和 jwt

时间:2023-03-29
本文介绍了Dotnet core 2.0 身份验证多模式身份 cookie 和 jwt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 dotnet core 1.1 asp 中,我能够通过执行以下操作来配置和使用身份中间件和 jwt 中间件:

In dotnet core 1.1 asp, I was able to configure and use identity middleware followed by jwt middleware by doing the following:

  app.UseIdentity();
  app.UseJwtBearerAuthentication(new JwtBearerOptions() {});

这已经改变了,我们使用以下实现中间件:

This has now changed in that we implement the middleware with:

   app.UseAuthentication();

设置的配置是通过 Startup.cs 的 ConfigureServices 部分完成的.

Configuration of the settings is done via the ConfigureServices section of Startup.cs.

迁移文档中有一些关于使用授权模式的参考:

There are some references to the use of authorization schema's in the migration documentation:

https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x#authentication-middleware-and-services

在 2.0 项目中,身份验证是通过服务配置的.每个身份验证方案在 ConfigureServices 方法中注册启动.cs.UseIdentity 方法被替换为 UseAuthentication.

In 2.0 projects, authentication is configured via services. Each authentication scheme is registered in the ConfigureServices method of Startup.cs. The UseIdentity method is replaced with UseAuthentication.

另外还有一个参考:

在 1.x 中,AutomaticAuthenticate 和 AutomaticChallenge 属性旨在设置在单个身份验证方案上.有没有很好的方法来执行这一点.

Setting Default Authentication Schemes

In 1.x, the AutomaticAuthenticate and AutomaticChallenge properties were intended to be set on a single authentication scheme. There was no good way to enforce this.

在 2.0 中,这两个属性已经作为单个 AuthenticationOptions 实例上的标志删除,并且已移至基本 AuthenticationOptions 类.属性可以在 AddAuthentication 方法调用中配置Startup.cs 的 ConfigureServices 方法:

In 2.0, these two properties have been removed as flags on the individual AuthenticationOptions instance and have moved into the base AuthenticationOptions class. The properties can be configured in the AddAuthentication method call within the ConfigureServices method of Startup.cs:

或者,使用 AddAuthentication 的重载版本方法来设置多个属性.在下面重载方法示例,默认方案设置为CookieAuthenticationDefaults.AuthenticationScheme.认证方案也可以在您的个人中指定[授权] 属性或授权策略.

Alternatively, use an overloaded version of the AddAuthentication method to set more than one property. In the following overloaded method example, the default scheme is set to CookieAuthenticationDefaults.AuthenticationScheme. The authentication scheme may alternatively be specified within your individual [Authorize] attributes or authorization policies.

在 dotnet core 2.0 中是否仍然可以使用多个身份验证模式?我无法获得尊重 JWT 配置(Bearer"模式)的策略,并且目前只有 Identity 与这两个配置一起工作.我找不到多个身份验证模式的任何示例.

Is it still possible in dotnet core 2.0 to use multiple authentication schemas? I cannot get the policy to respect the JWT configuration ("Bearer" schema), and only Identity is working at present with both configured. I can't find any samples of multiple authentication schemas.

我重新阅读了文档,现在明白了:

I've reread the documentation, and now understand that the:

app.UseAuthentication()

添加针对默认架构的自动身份验证.Identity 为您配置默认架构.

adds automatic authentication against a default schema. Identity configures the default schemas for you.

通过在 Startup.cs 配置中执行以下操作,我已经解决了似乎针对新 api 的黑客攻击的问题:

I have gotten around the issue with what seems like a hack working against the new api's by doing the following in Startup.cs Configure:

    app.UseAuthentication();
    app.Use(async (context, next) =>
    {
        if (!context.User.Identity.IsAuthenticated)
        {
            var result = await context.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
            if (result?.Principal != null)
            {
                context.User = result.Principal;
            }
        }

        await next.Invoke();
    });

这是执行此操作的正确方法,还是我应该利用框架、DI 和接口来自定义 IAuthenticationSchemeProvider 的实现?

Is this the correct way to do this, or should I be utilising the framework, DI and interfaces for custom implementations of IAuthenticationSchemeProvider?

编辑 - 实现的更多细节以及在哪里可以找到它.

Edit - Futher details of the implementation and where to find it.

JWT 配置可以在这里找到,我正在使用策略来定义授权,其中包括接受的身份验证模式:

The JWT Config can be found here, and I am using policies to define the authorization, which include the accepted auth schema's:

https://github.com/Arragro/ArragroCMS/blob/master/src/ArragroCMS.Management/Startup.cs

自定义中间件仍在实施.Auth 控制器在这里:

Custom middleware is still implemented. The Auth controller is here:

https://github.com/Arragro/ArragroCMS/blob/master/src/ArragroCMS.Web.Management/ApiControllers/AuthController.cs

它使用应用程序生成的 API 密钥来获得对数据的只读访问权限.您可以在此处找到使用该策略的控制器的实现:

It uses API Keys generated by the app to get read only access to data. You can find the implementation of a controller utilising the policy here:

https://github.com/Arragro/ArragroCMS/blob/master/src/ArragroCMS.Web.Management/ApiControllers/SitemapController.cs

更改数据库连接字符串以指向您的 SQL Server,然后运行应用程序.它会自动迁移数据库并配置管理员用户 (support@arragro.com - ArragroPassword1!).然后转到菜单栏中的设置"选项卡并单击配置 JWT ReadOnly API 密钥设置"以获取密钥.在 postman 中,通过配置新选项卡并将其设置为 POST 并使用以下地址获取 jwt 令牌:

Change the DB Connection string to point to your SQL Server, and run the application. It migrates the DB automatically and configures an admin user (support@arragro.com - ArragroPassword1!). Then go to the Settings tab in the menu bar and click "Configure the JWT ReadOnly API Key Settings" to get a key. In postman, get a jwt token by configuring a new tab and setting it to POST with the following address:

http://localhost:5000/api/auth/readonly-token

提供标头:Content-Type: application/json

Supply the headers: Content-Type: application/json

供应身体:

{
    "apiKey": "the api token from the previous step"
}

复制响应中的令牌,然后在邮递员中使用以下内容:

Copy the token in the response, and then use the following in postman:

http://localhost:5000/api/sitemap/flat

Authorization: "bearer - The token you received in the previous request"

由于自定义中间件,它最初可以工作.把上面提到的代码注释掉,再试一次,就会收到401.

It will work inititally because of the custom middleware. Comment out the code mentioned above and try again and you will receive a 401.

编辑 -@DonnyTian 下面的回答涵盖了我在他的评论中的解决方案.我遇到的问题是在 UseMvc 上设置默认策略,但不提供架构:

Edit -@DonnyTian's answer below covers my solution in his comments. The problem I was having was setting a default policy on UseMvc, but not supplying the schema's:

    services.AddMvc(config =>
    {
        var defaultPolicy = new AuthorizationPolicyBuilder(new[] { JwtBearerDefaults.AuthenticationScheme, IdentityConstants.ApplicationScheme })
                         .RequireAuthenticatedUser()
                         .Build();
        config.Filters.Add(new AuthorizeFilter(defaultPolicy));
        config.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
        config.Filters.Add(new ValidateModelAttribute());
    });

按照建议,这无需自定义中间件即可工作.

Following the advice, this works without custom middleware.

推荐答案

Asp.Net Core 2.0 绝对支持多种认证方案.您可以尝试在 Authorize 属性中指定架构,而不是使用身份验证中间件进行黑客攻击:

Asp.Net Core 2.0 definitely support multiple authentication schemes. Rather than a hacking with authenticate middleware, you can try to specify the schema in Authorize attribute:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

我试了一下,效果很好.假设您已添加 Identity 和 JWT,如下所示:

I gave a try and it worked fine. Assuming you have added both Identity and JWT as below:

services.AddIdentity<ApplicationUser, ApplicationRole>()
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

由于 AddIdentity() 已经将 cookie 身份验证设置为默认模式,我们必须在控制器的 Authorize 属性中指定模式.目前,我不知道如何覆盖 AddIdentity() 设置的默认模式,或者我们最好不要这样做.

Since AddIdentity() already set cookie authentication as the default schema, we have to specify schema in Authorize attribute of controllers. For now, I have no idea how to overwrite the default schema set by AddIdentity(), or maybe we'd better not to do that.

一种解决方法是编写一个派生自 Authorize 并将 Bearer 作为默认架构的新类(您可以将其称为 JwtAuthorize),因此您不需要每次都要指定.

A work around is to compose a new class (you can call it JwtAuthorize) that derives from Authorize and have Bearer as the default schema, so you don't have to specify it every time.

更新

找到了覆盖 Identity 默认身份验证方案的方法!

Found the way to override Identity default authentication scheme!

而不是下面的行:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

使用下面的重载来设置默认架构:

Use below overload to set default schema:

services.AddAuthentication(option =>
                {
                    option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>....

更新 2如评论中所述,您可以通过将 Identity 和 JWT auth 连接在一起来启用它们.<代码>[授权(AuthenticationSchemes = "Identity.Application" + "," + JwtBearerDefaults.AuthenticationScheme)]

UPDATE 2 As mentioned in comments, you can enable both Identity and JWT auth by join them together. [Authorize(AuthenticationSchemes = "Identity.Application" + "," + JwtBearerDefaults.AuthenticationScheme)]

这篇关于Dotnet core 2.0 身份验证多模式身份 cookie 和 jwt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:JWT 验证失败 下一篇:JwtSecurityToken 不会过期

相关文章