在this 上有Jwt-Rsa-Hmac 身份验证 的示例代码网站 this repo 。
我一直在尝试将它从 Asp.Net Core 1 转换为 Asp.Net Core 2。
我创建了一个新的 Asp.Net Cor 2.1 项目,在搜索了它需要的更改之后,我想出了 this代码。
它确实创建了 token ,但在使用 token 时我总是得到 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
最佳答案
示例存储库中的问题是,您正在创建新的 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 .
关于c# - 将 Asp.Net Core 1 转换为 Core 2 后 Jwt 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56054314/