本文介绍了Dotnet 核心 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.

另外还有一个参考:

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

在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,然后运行应用程序.它会自动迁移数据库并配置管理员用户([email protected] - 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 ([email protected] - 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 2As mentioned in comments, you can enable both Identity and JWT auth by join them together.[Authorize(AuthenticationSchemes = "Identity.Application" + "," + JwtBearerDefaults.AuthenticationScheme)]

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

08-20 08:15