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

Wij*_*tha 4 asp.net jwt asp.net-web-api asp.net-identity .net-core-2.0

在我的Asp.Net核心web api中,我使用Identity与Jwt承载认证.它没有任何大惊小怪,工作顺利.这是代码,

ConfigureServices():

 services.AddIdentity<ApplicationUser, IdentityRole<int>>()
            .AddEntityFrameworkStores<DataContext, int>()
            .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

配置():

  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
                }
            });
Run Code Online (Sandbox Code Playgroud)

今天我升级到.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"))
                };
            });
Run Code Online (Sandbox Code Playgroud)

配置()

app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

现在身份验证无效.看起来它在内部配置为使用Cookie身份验证.

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

谢谢,

小智 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;
})
Run Code Online (Sandbox Code Playgroud)