Dotnet 核心 2.0 将身份与 JwtBearer 身份验证结合使用

Dotnet core 2.0 Use Identity with JwtBearer Authentication

在我的 Asp.Net 核心网络 api 中,我使用带有 Jwt 承载身份验证的身份。它工作顺利,没有任何大惊小怪。这是代码,

ConfigureServices():

 services.AddIdentity<ApplicationUser, IdentityRole<int>>()
            .AddEntityFrameworkStores<DataContext, int>()
            .AddDefaultTokenProviders();

配置():

  app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer = "localhost:4200",
                    ValidAudience = "localhost:4200",
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperSecretKey_GetThisFromAppSettings")),
                    ValidateLifetime = true
                }
            });

今天我升级到了 .net core 2.0 和整个技术栈。从可用的有限帮助中,我修改了这样的代码..

ConfigureServices()

 services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<DataContext>()
                .AddDefaultTokenProviders();   



services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Authority = "localhost:4200";
                    options.Audience = "localhost:4200";
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidateLifetime = true,
                    ValidIssuer = "localhost:4200",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperSecretKey_GetThisFromAppSettings"))
                };
            });

配置()

app.UseAuthentication();

现在身份验证不起作用。看起来其内部配置为使用 Cookie 身份验证。

有没有其他人遇到过这种情况?非常感谢对此的任何帮助!

谢谢,

如果我从 MS 站点上理解正确的话

https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x

Identity 添加cookies 并设置cookie scheme 的默认身份验证。 尝试更改您的

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

services.AddAuthentication(o => {
  o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})

在回答问题时:

Do you know how to stop default redirection to login page during an unauthorized access?

我在 PioneerCode 中找到了这个博客 post,用于 dotnet 核心 1,可能会有帮助。

这就是我实现它的方式并且它起作用了:

services.ConfigureApplicationCookie(options => { options.LoginPath = "/api/login";
    options.Events = new CookieAuthenticationEvents
    {
      OnRedirectToLogin = ctx =>
      {
        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
        {
          ctx.Response.StatusCode = 401;
          return Task.FromResult<object>(null);
        }

        ctx.Response.Redirect(ctx.RedirectUri);
        return Task.FromResult<object>(null);
      }
    };
  });