【发布时间】:2020-05-18 22:30:24
【问题描述】:
我有一个使用 JWT 进行验证的 ASP.NET Core MVC 应用程序
我在启动类中添加了身份验证,使用我们的 appsettings 文件中的令牌密码来验证令牌。
services.Configure<ApplicationSettings>(Configuration.GetSection("AppSettings"));
var key = System.Text.Encoding.UTF8
.GetBytes(Configuration.GetSection("AppSettings:Token").Value);
services.AddAuthentication(x => {
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x => {
x.RequireHttpsMetadata = false;
x.SaveToken = false;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
};
});
并添加授权中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("MyPolicy");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
现在,当用户尝试登录时,将运行以下控制器方法,使用相同的令牌密钥生成令牌。
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
{
var user = await _userManager.FindByNameAsync(userForLoginDto.Username);
var result = await _signInManager
.CheckPasswordSignInAsync(user, userForLoginDto.Password, false);
if (result.Succeeded)
{
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim("UserID",user.Id.ToString())
}),
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8
.GetBytes(appSettings.Token)), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(securityToken);
return Ok(new { token });
}
return Unauthorized();
}
所以当用户登录时,会生成一个令牌并发回给客户端。
此时我希望我可以将[Authorize] 属性添加到控制器方法,然后MVC 框架将在http 标头中查找有效令牌。所以我创建了一个测试控制器方法
[HttpGet]
[Authorize]
public IActionResult Get()
{
return Ok("Test");
}
并发送一个与测试控制器方法相对应的请求,其中 Authorization 标头设置为Bearer <Token>,但我仍然得到未经授权的 401。
谁能解释为什么会发生这种情况?如果您需要更多信息,请告诉我。
【问题讨论】:
-
您发送的令牌是否有效(签入jwt.io)?
-
@auburg 是的
标签: asp.net-core asp.net-identity