jwt-rsa-hmac身份验证在此网站上使用此回购。
我一直在尝试将其从ASP.NET Core 1转换为ASP.NETCore2。
我创建了一个新的ASP.NET COR 2.1项目,在搜索所需的更改后,我提出了此代码。
它确实会创建令牌,但是使用令牌时,我总是会得到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();
}
,其余的示例代码在此存储库中。
链接我已经研究了:
从ASP.NET Core 1迁移到ASP.NET Core 2
样本存储库中的问题是,您在此处创建新的JwtBearerOptions
。
我将其更改为此,它可以正常工作
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());
}
};
});
我已经给您发送了一个plup Qurequest。
我在.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,
};
});