gpt4 book ai didi

c# asp.net core Bearer错误="invalid_token"

转载 作者:太空狗 更新时间:2023-10-29 21:37:28 26 4
gpt4 key购买 nike

有人可以帮我解决这个问题吗?我正在使用 Postman 测试 API

我正在学习有关 asp.net core 的教程。

我现在正在处理它的身份验证部分。

我真的不明白错误的原因是什么。

在教程中,它有一个登录并返回 token 。

这是登录代码。哪个有效。我知道这是有效的,因为它返回一个 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();

我还在值 Controller 中启用了[Authorize]

[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase

这是postman的截图

enter image description here

我遵循了教程。我粘贴从登录收到的 token 。但它给了我错误

WWW-Authenticate →Bearer error="invalid_token", error_description="The audience is invalid"

如果 token 来自登录,为什么错误会给我 invalid token?我该如何解决?我一直在寻找一段时间,但我无法自己解决这个问题。谢谢。

最佳答案

更新到 Microsoft.AspNetCore.Authentication.JwtBearer v6.0.0+

后,我在 dotnet 6 中遇到了这个问题

修复:安装 nugetSystem.IdentityModel.Tokens.Jwt Version="6.16.0"

关于c# asp.net core Bearer错误="invalid_token",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54395859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com