将Asp.Net Core 1转换为Core 2后Jwt无法正常工作

时间:2019-05-09 07:31:26

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

this网站上有一个{strong> Jwt-Rsa-Hmac身份验证的示例代码,其中有this个仓库。
我一直在尝试将其从Asp.Net Core 1转换为Asp.Net Core2。
我创建了一个新的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存储库中。

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

2 个答案:

答案 0 :(得分: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,
                };

            });

答案 1 :(得分:2)

示例存储库中的问题是,您正在创建新的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