I'm generating the JWT token, and then trying to authorize by it, but i'm still getting 401 Unauthorized That's how i generate JWT:
string IAccountService.GenerateJwt(LoginDto dto)
{
var user = _context.Users.FirstOrDefault(u => u.EMail == dto.Email);
if (user == null)
{
throw new BadRequestException("Invalid user name or password", new Exception());
}
var resault = _passwordHasher.VerifyHashedPassword(user, user.Password, dto.Password);
if (resault == PasswordVerificationResult.Failed)
{
throw new BadRequestException("Invalid user name or password", new Exception());
}
var claims = new List<Claim>() {
// new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
//new Claim(ClaimTypes.Name, user.Name)
new Claim("Id", user.Id.ToString()),
new Claim("Name", user.Name)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("JwtSettings:Token").Value!));
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.Now.AddDays(1),
signingCredentials: cred
);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
return jwt;
}
This is my program.cs:
builder.Services.AddAuthentication().AddJwtBearer();
...
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<ErrorHandlingMiddleware>();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
I'm using postman and selecting bearer token then passing the token from API
I tried to debbug it, but nothink helped enter image description here
I tried this https://nestenius.se/2023/06/02/debugging-jwtbearer-claim-problems-in-asp-net-core/ Output: enter image description here But when i tried to get claims it shows nothing.
I have decoded the token you provided, which shows that your JWT generation method is correct. The token contains claim: id and name. Therefore, when using postman for API testing,confirm whether the latest token is used. If you have used the latest token for API testing and the problem still exists, during the process of parsing the token, you need to use the same configuration as when generating the token to verify the token. TokenValidationParameters is a set of parameters used to verify the JWT Token. It contains a series of properties that specify various settings when validating the JWT Token, such as signing key, issuer verification, audience verification, lifecycle verification, etc., so you need to use the same configuration when generating the token to verify the token cards, here is an example you can use as a reference: