Ram*_*hon 7 c# postman asp.net-core
有人可以帮我解决这个问题吗?我正在使用Postman测试API
我正在关注有关asp.net核心的教程。
我现在在认证部分。
我不太了解发生错误的原因。
在本教程中,它具有登录名并返回令牌。
这是登录代码。哪个在工作。我知道这是有效的,因为它返回令牌。我也尝试使用无效的登录名。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)
});
}
Run Code Online (Sandbox Code Playgroud)
然后,本教程的下一部分是限制访问。用户应先登录才能查看内容。
下面是代码
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
};
});
Run Code Online (Sandbox Code Playgroud)
然后启用
app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)
我还在[Authorize]Values Controller中启用了
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
Run Code Online (Sandbox Code Playgroud)
这是邮递员的屏幕截图
我遵循了教程。我粘贴从登录中收到的令牌。但这给了我错误
WWW-Authenticate ?Bearer error="invalid_token", error_description="The audience is invalid"
Run Code Online (Sandbox Code Playgroud)
invalid 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,
ValidateAudience = false
};
});
Run Code Online (Sandbox Code Playgroud)
小智 39
dotnet 6我在更新后遇到了这个问题Microsoft.AspNetCore.Authentication.JwtBearer v6.0.0+
修复:安装nuget包System.IdentityModel.Tokens.Jwt Version="6.16.0"
我最近使用 JWT 令牌做了类似的事情,它与 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);
Run Code Online (Sandbox Code Playgroud)
我的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
};
});
Run Code Online (Sandbox Code Playgroud)
注意:适当更改发行者和密钥。
小智 6
我有一个类似的问题,即 .net Core 3 API 无法验证自己的令牌。
我的解决方案是在 Startup/Configure() 中,将 app.UseAuthentication() 放在 app.UseAuthorization() 之前。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
app.UseAuthorization();
}
Run Code Online (Sandbox Code Playgroud)