asp.net - Dotnet core 2.0 使用身份与 JwtBearer 身份验证

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

在我的 Asp.Net core Web api 中,我使用 Identity 和 Jwt 承载身份验证。它工作得很顺利,没有任何麻烦。这是代码,

配置服务():

 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 和整个技术栈。从可用的有限帮助中,我修改了这样的代码..

配置服务()

 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://learn.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;
})

关于asp.net - Dotnet core 2.0 使用身份与 JwtBearer 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904955/

相关文章:

c# - 如何在使用 asp.net Identity 关闭浏览器后保留登录信息?

asp.net - 应将 Web 应用程序的哪些部分移至 Azure 中的 WorkerRole

c# - 为什么 "Session_end"不起作用?

c# - asp.net Web 应用程序中的 Facebook 注销按钮

c# - Stormpath OAuth 2.0 不支持的授权类型

asp.net - 重新使用现有 Microsoft Identity 用户表时密码(哈希)不匹配

c# - 如何在点击asp.net按钮时自动点击html按钮

c# - angularjs传递数据有列表数据

c# - 单独项目下的 ASP.NET Web API 帮助页面

asp.net - Blazor ASP.Net Core 3.1 Web API 发布时返回 404 错误