this has been bugging me and I can't find the cause with my lack of knowledge.
below is a success request in postman, the right side is the c# code for it. I also got success result in swagger.
however, I keep on getting Unauthorized response
Token has been validated and correct
Tried ChatGPT, but all suggestions have the same result.
WebAPI Program.cs
// JWT configuration
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
//options.RequireHttpsMetadata = false;
//options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your_issuer",
ValidAudience = "your_audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("e91ec378-3c0f-4a32-98d1-573f158eb12a"))
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy(IdentityData.AdminPolicyName, policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim(IdentityData.AdminUserClaimName, "ADMN");
});
});
//....
app.UseAuthentication();
app.UseAuthorization();
Controller
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
[Authorize]
[HttpPost("Authenticate")]
[ProducesResponseType(typeof(ReturnObject), (int)HttpStatusCode.OK)]
public ActionResult<ReturnObject> Authenticate([FromBody] RequestObject body)
{
}
}
Edit This is the code for generating JWT
[AllowAnonymous]
[HttpPost("GenerateToken")]
public IActionResult GenerateToken([FromBody] IdentityClaims request)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, request.Username),
new Claim(ClaimTypes.Email, request.Email),
new Claim("Role", request.Role)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("e91ec378-3c0f-4a32-98d1-573f158eb12a"));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "your_issuer",
audience: "your_audience",
claims: claims,
expires: DateTime.Now.AddDays(1),
signingCredentials: credentials
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
return Ok(new { Token = tokenString });
}
Got the same Unauthorize for the GetUser, but success in Postman and Swagger
postman
swagger (bearer token in the Authorize option)