我已经在这个问题上奋斗了几个小时,但似乎无法追踪到为什么所有调用我的启用[授权]
的端点都会失败并返回401。
在我的.Net Core 2.2 Web API项目中,在Startup.cs文件中,我已经设置了身份验证:
public void ConfigureServices(IServiceCollection services)
{
var jwtSettings = new JwtSettings();
Configuration.Bind(nameof(jwtSettings), jwtSettings);
services.AddSingleton(jwtSettings);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// Add the JWT Bearer token configuration
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("craigcraigcraigcraigcraigcraig")),//jwtSettings.Secret)),
ValidateIssuer = false,
ValidateAudience = false,
RequireExpirationTime = false,
ValidateLifetime = true
};
});
services.AddSwaggerGen(x =>
{
x.SwaggerDoc("v1", new Info { Title = "My Backend", Version = "v1" });
var security = new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[0]}
};
x.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "JWT Authorisation header using the bearer scheme",
Name = "Authorisation",
In = "header",
Type = "apiKey"
});
x.AddSecurityRequirement(security);
});
}
- 注意,我硬编码了我的密钥,因为我不确定那是否是问题所在。
然后,在配置中,我告诉我的应用程序要使用 UseAuthentication
,并确保Swagger知道我需要一些授权帮助。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
// This is getting the seetings from a 'SwaggerOptions' section within appSettings.[Env].json, and bind that data to the SwaggerOptions class.
var swaggerOptions = new Options.SwaggerOptions();
Configuration.GetSection(nameof(Options.SwaggerOptions)).Bind(swaggerOptions);
app.UseSwagger(option => { option.RouteTemplate = swaggerOptions.JsonRoute; });
app.UseSwaggerUI(option => { option.SwaggerEndpoint(swaggerOptions.UiEndpoint, swaggerOptions.Description); });
app.UseMvc();
}
我有一个端点,它接收用户名和密码。我进行了一些检查,如果用户名和密码正确,我会生成一个令牌:
private string GenerateToken(UserDto user)
{
var key = Encoding.ASCII.GetBytes("craigcraigcraigcraigcraigcraig");// config.GetSection("JwtSettings").GetSection("Secret").Value);
var singingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key);
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.GivenName, user.Firstname),
new Claim(JwtRegisteredClaimNames.FamilyName, user.Surname),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim("id", user.Id.ToString())
}),
Expires = DateTime.UtcNow.AddHours(2),
SigningCredentials = new SigningCredentials(singingKey, SecurityAlgorithms.HmacSha256)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
这个token返回我的Swagger前端,看起来没问题。
我在Swagger中收到的响应:
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtZUBoZXJlLmNvbSIsImdpdmVuX25hbWUiOiJDcmFpZyIsImZhbWlseV9uYW1lIjoiU21pdGgiLCJqdGkiOiI2ZWJkYjk4MC1iZWM0LTQzMTctOTkwYy1kN2Q3Mzk4MmY3Y2QiLCJlbWFpbCI6Im1lQGhlcmUuY29tIiwiaWQiOiIzMjA3YWZkOC1kMTU5LTQwNTgtYmVlNS1kZmRmYzBhYzBlODgiLCJuYmYiOjE1NjM4NzI4ODYsImV4cCI6MTU2Mzg4MDA4NiwiaWF0IjoxNTYzODcyODg2fQ.FGuc5qU-3QoIJBodYf6yi3Wi9Q9RS2kdp0NHaCrplaY"
}
我在jwt.ms上验证过这个:
所以现在,我生成了一个有效的JWT(我想)。
我有一个测试端点。我在Swagger中“授权”(单击授权,键入'Bearer'并粘贴令牌)。
当我执行我的 'Authorize' 端点时,返回以下内容:
curl -X GET "https://localhost:44370/api/accounts" -H "accept: application/json" -H "Authorisation: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtZUBoZXJlLmNvbSIsImdpdmVuX25hbWUiOiJDcmFpZyIsImZhbWlseV9uYW1lIjoiU21pdGgiLCJqdGkiOiI2ZWJkYjk4MC1iZWM0LTQzMTctOTkwYy1kN2Q3Mzk4MmY3Y2QiLCJlbWFpbCI6Im1lQGhlcmUuY29tIiwiaWQiOiIzMjA3YWZkOC1kMTU5LTQwNTgtYmVlNS1kZmRmYzBhYzBlODgiLCJuYmYiOjE1NjM4NzI4ODYsImV4cCI6MTU2Mzg4MDA4NiwiaWF0IjoxNTYzODcyODg2fQ.FGuc5qU-3QoIJBodYf6yi3Wi9Q9RS2kdp0NHaCrplaY"
这似乎表明它发送了JWT。
但是,我也得到了401的响应:
date: Tue, 23 Jul 2019 09:12:20 GMT
server: Microsoft-IIS/10.0
status: 401
www-authenticate: Bearer
x-powered-by: ASP.NET
x-sourcefiles: =?UTF-8?B?QzpcU3RvcmFnZVxTb2Z0d2FyZSBSZXBvc2l0b3JpZXNcUGVyc29uYWxcQWNjdUZpbmFuY2VWMkJhY2tlbmRcQWNjdUZpbmFuY2UgQmFja2VuZFxBUElcYXBpXGFjY291bnRz?=
我不确定如何调试这个问题。显然我的代码有问题,但我无法找出具体位置。令牌似乎生成了,但验证失败。是否有谁能发现问题或者告诉我在哪里进行调试,为什么会收到"401"错误?