有人能帮我解决这个问题吗?我正在使用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-01-28 13:31:37
我最近使用JWT token做了类似的事情,它与Postman一起工作得很好。我创建JWT令牌的方法略有不同,在您的例子中,问题可能是由于没有指定 issuer和audience。
你能试着像下面这样。
var claims = new List<Claim>
{
new Claim(ClaimTypes.WindowsAccountName, this.User.Identity.Name)
};
Claim userIdClaim = new Claim("UserId", "12345");
claims.Add(userIdClaim);
//Avoid Replay attack
claims.Add(new Claim(ClaimTypes.GivenName, "User GivenName"));
claims.Add(new Claim(ClaimTypes.Surname, "UserSurname"));
claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
string[] roles = "Role1,Role2,Role23".Split(",");
foreach (string role in roles)
{
claims.Add(new Claim(role, ""));
}
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("veryVerySecretKey"));
var key1 = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ASEFRFDDWSDRGYHF"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var encryptingCreds = new EncryptingCredentials(key1, SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256);
var handler = new JwtSecurityTokenHandler();
var t = handler.CreateJwtSecurityToken();
var token = handler.CreateJwtSecurityToken("http://localhost:61768/", "http://localhost:61768/"
, new ClaimsIdentity(claims)
, expires: DateTime.Now.AddMinutes(1)
, signingCredentials: creds
, encryptingCredentials :encryptingCreds
, notBefore:DateTime.Now
, issuedAt:DateTime.Now);
return new JwtSecurityTokenHandler().WriteToken(token);我的ConfigureServices看起来像
services.AddAuthentication()
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "http://localhost:61768/",
ValidAudience = "http://localhost:61768/",
TokenDecryptionKey= new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ASEFRFDDWSDRGYHF")),
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("veryVerySecretKey")),
ClockSkew = TimeSpan.Zero
};
});注意:适当更改颁发者和密钥。
发布于 2020-08-08 17:30:37
我遇到了一个类似的问题,.net Core3API无法验证自己的令牌。
我的解决方案是在Startup/Configure()中,将app.UseAuthentication()放在app.UseAuthorization()之前。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
app.UseAuthorization();
}发布于 2019-01-28 14:25:07
您收到的错误与受众有关,您应该在选项中包括ValidAudience或将ValidateAudience设置为false。
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,
ValidateAudience = false
};
});https://stackoverflow.com/questions/54395859
复制相似问题