Dotnet Core 2.0身份验证多个架构身份cookie和jwt [英] Dotnet core 2.0 authentication multiple schemas identity cookies and jwt

查看:154
本文介绍了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:

在2.0项目中,身份验证是通过服务配置的.每个 身份验证方案已在以下服务器的ConfigureServices方法中注册 Startup.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.

此外,还有对以下内容的引用:

Additionally there is a reference to:

设置默认身份验证方案

在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基类.属性 可以在 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配置(承载"架构)的策略,目前只有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()

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

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

我已经通过在Startup.cs Configure中执行以下操作来解决似乎与新api兼容的hack问题:

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 Config,我正在使用策略来定义授权,其中包括接受的auth模式:

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. 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. com/Arragro/ArragroCMS/blob/master/src/ArragroCMS.Web.Management/ApiControllers/SitemapController.cs

更改数据库连接字符串以指向您的SQL Server,然后运行该应用程序.它会自动迁移数据库并配置一个管理员用户(support@arragro.com-ArragroPassword1!).然后转到菜单栏中的设置"选项卡,然后单击配置JWT ReadOnly API密钥设置"以获取密钥.在邮递员中,通过配置新标签并将其设置为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.

一种解决方法是组成一个新类(可以将其称为JwtAuthorize),该类派生自Authorize并具有 Bearer 作为默认架构,因此您不必每次都指定它时间.

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.

更新

找到了替代身份默认身份验证方案的方法!

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 如评论中所述,您可以通过将身份验证和JWT身份验证结合在一起来启用它们. [Authorize(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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