asp.net - Dotnet core 2.0身份验证多模式身份cookie和jwt

标签 asp.net authentication asp.net-identity .net-core jwt

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

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

现在情况发生了变化,我们通过以下方式实现中间件:

   app.UseAuthentication();

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

迁移文档中引用了一些授权架构的使用:

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

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.

此外还有一个引用:

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.

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:

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 配置(“承载”模式)的策略,并且目前只有身份在配置两者的情况下工作。我找不到任何多个身份验证模式的示例。

编辑:

我重新阅读了文档,现在了解到:

app.UseAuthentication()

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

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

    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 和接口(interface)来自定义实现 IAuthenticationSchemeProvider?

编辑 - 实现的更多详细信息以及在哪里可以找到它。

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

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

自定义中间件仍在实现。 Auth Controller 在这里:

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

它使用应用程序生成的 API key 来获取对数据的只读访问权限。您可以在此处找到利用该策略的 Controller 的实现:

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

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

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

提供 header :内容类型:application/json

供应 body :

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

复制响应中的 token ,然后在 postman 中使用以下内容:

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

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

由于自定义中间件,它最初会起作用。注释掉上面提到的代码并重试,您将收到 401。

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

    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());
    });

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

最佳答案

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

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

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

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

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

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

更新

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

而不是下面的行:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

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

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

更新2 正如评论中提到的,您可以通过将 Identity 和 JWT 身份验证连接在一起来启用它们。 [Authorize(AuthenticationSchemes = "Identity.Application"+ ","+ JwtBearerDefaults.AuthenticationScheme)]

关于asp.net - Dotnet core 2.0身份验证多模式身份cookie和jwt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45778679/

相关文章:

asp.net-core - .NET Core Identity Framework 和 Telegram Login Widget(无数据库)

python - 使用 Python 通过浏览器登录 facebook 和 google,无需使用其 API

c# - ASP.NET Identity userid 是顺序 guid

c# - 外键可能导致循环或多个级联路径

c# - 在控制台应用程序中人为填充 HttpContext 对象

python - Django:使用参数重定向到 View

swift - 虽然我有正确的信息,但有一个线程 1 : Signal brt

c# - User.IsInRole() 仅在 Controller 中始终返回 false

c# - 如何禁用 FileUpload 控件中的文件夹导航

asp.net - 在 SQL SERVER 中使用一个查询更新多个表