【问题标题】:Jwt not working after converting Asp.Net Core 1 to Core 2将 Asp.Net Core 1 转换为 Core 2 后 Jwt 无法正常工作
【发布时间】:2019-09-26 23:43:29
【问题描述】:

this 网站上有一个用于 Jwt-Rsa-Hmac 身份验证 的示例代码,this repo。
我一直在尝试将其从 Asp.Net Core 1 转换为 Asp.Net Core 2。
我创建了一个新的 Asp.Net Cor 2.1 项目,在搜索了所需的更改后,我想出了this 代码。
它确实创建了令牌,但在使用令牌时,我总是得到401(未经授权)。
已经几天了,没有成功...
如果有人可以帮助我,我将不胜感激。
这是我的启动课:

 public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }
        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<JwtSettings>(Configuration.GetSection("jwt"));
            var x = services.AddSingleton<IJwtHandler, JwtHandler>();

            var sp = services.BuildServiceProvider();
            var jwtHandler = sp.GetService<IJwtHandler>();
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = jwtHandler.Parameters;
            });
            services.AddMvc();

        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseDeveloperExceptionPage();
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseAuthentication();
            app.UseMvc();
        }    

其余的示例代码在this repo 中。

我已经研究过的链接:
Token Authentication stopped working after migration from ASP.NET Core 1 to ASP.NET Core 2

【问题讨论】:

    标签: c# asp.net-core jwt rsa hmac


    【解决方案1】:

    您的示例存储库中的问题是,您正在创建新的 JwtBearerOptions here

    我把它改成了这个,它工作得很好

    services.AddAuthentication(o =>
    {
        o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(o =>
    {
    
        o.IncludeErrorDetails = true;
        o.RequireHttpsMetadata = false;
        o.TokenValidationParameters = jwtHandler.Parameters;
        o.Events = new JwtBearerEvents()
        {
            OnAuthenticationFailed = c =>
            {
                c.NoResult();
    
                c.Response.StatusCode = 401;
                c.Response.ContentType = "text/plain";
    
                return c.Response.WriteAsync(c.Exception.ToString());
            }
    
        };
    });
    

    我给你发了pull-request

    【讨论】:

      【解决方案2】:

      我在 .netcore2.1 中使用了这个设置并为我工作:

      services.AddAuthentication(options =>
                  {
                      options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                      options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
                      options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                  }).AddJwtBearer(cfg =>
                  {
                      cfg.SaveToken = true;
                      cfg.TokenValidationParameters = new TokenValidationParameters
                      {
                          ValidIssuer = Configuration["BearerTokens:Issuer"],
                          ValidAudience = Configuration["BearerTokens:Audience"],
                          IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["BearerTokens:Key"])),
      
                          ValidateIssuer = true,
                          ValidateAudience = true,
                          ValidateLifetime = true,
                          ValidateIssuerSigningKey = true,
                      };
      
                  });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        • 2020-09-27
        • 2020-08-17
        • 2020-10-07
        • 2018-01-11
        • 2020-05-01
        相关资源
        最近更新 更多