有人能帮我解决这个问题吗?我正在使用Postman测试API
我正在学习一个关于asp.net核心的教程。
我现在负责它的身份验证部分。
我真的不明白这个错误的原因是什么。
在本教程中,它有一个登录并返回token。
这是登录的代码。这是有效的。我知道这是有效的,因为它返回一个令牌。我还尝试使用无效的登录。它返回401 Unauthorized,但是当我使用在数据库中找到的正确登录凭据时。它返回token
[HttpPost("login")]
public async Task<IActionResult> Login(UserForLoginDto userForLoginDto)
{
var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);
if (userFromRepo == null)
return Unauthorized();
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
new Claim(ClaimTypes.Name, userFromRepo.Username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return Ok(new {
token = tokenHandler.WriteToken(token)
});
}然后,本教程的下一部分是限制访问。用户应先登录才能查看内容。
下面是代码
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>{
options.TokenValidationParameters = new TokenValidationParameters{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false
};
});然后启用
app.UseAuthentication();我还在Values控制器中启用了[Authorize]
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase这是邮递员的截图

我遵循了教程。我粘贴从登录收到的令牌。但是它给了我一个错误
WWW-Authenticate →Bearer error="invalid_token", error_description="The audience is invalid"如果令牌来自登录,为什么错误会显示invalid token?我该如何解决这个问题?我已经找了一段时间了,但我自己解决不了这个问题。谢谢。
发布于 2019-10-28 04:27:57
我也有同样的问题。请注意,配置函数中的顺序。
app.usemvc ();应该在底部。如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}https://stackoverflow.com/questions/54395859
复制相似问题