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

时间:2017-08-27 12:28:29

标签: asp.net asp.net-web-api asp.net-identity jwt .net-core-2.0

在我的Asp.Net核心web api中,我使用Identity与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身份验证。

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

谢谢,

2 个答案:

答案 0 :(得分:7)

如果我从MS网站上正确理解

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

Identity添加cookie并将默认身份验证设置为cookie方案。 尝试更改

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

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

答案 1 :(得分:1)

回答这个问题:

  

您是否知道如何在未经授权的访问期间停止默认重定向到登录页面?

我发现这篇由PioneerCode发布的针对dotnet core 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);
      }
    };
  });