【发布时间】:2019-06-21 02:14:49
【问题描述】:
有人可以帮我解决这个问题吗?我正在使用 Postman 测试 API
我正在关注一个关于 asp.net core 的教程。
我现在正处于其身份验证部分。
我真的不明白错误的原因是什么。
在教程中,它有一个登录并返回令牌。
这是登录代码。哪个正在工作。我知道这是有效的,因为它返回一个令牌。我也尝试使用无效的登录。它返回401 Unauthorized 但是当我使用在数据库中找到的正确登录凭据时。它返回令牌
[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();
我还在值控制器中启用了[Authorize]
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
这是邮递员的截图
我按照教程进行操作。我粘贴从登录中收到的令牌。但它给了我错误
WWW-Authenticate →Bearer error="invalid_token", error_description="The audience is invalid"
如果令牌来自登录,为什么错误会给我invalid token?我该如何解决?我一直在寻找一段时间,但我自己无法解决这个问题。谢谢。
【问题讨论】:
-
如果我省略了 contentType,就会出现这个错误
-
@daremachine。抱歉,我不明白 contentType。请问能不能展开。我来自WPF。我真的不明白
-
你能显示你的 api/values,你有没有为此设置任何授权策略?
-
@PSK 是的。授权策略已启用。请检查帖子。我更新了它,忘了提及它。对不起
-
@Ramonbihon 我想知道你是如何解决这个问题的?
标签: c# asp.net-core postman