C
C#2y ago
_vegabyte_

✅ JWT Authorization Issue with .NET Core Web API

Hello everyone, I am currently working on an ASP.NET Core Web API that uses JWT for authorization. I have a GetAllUsersAsync endpoint that needs to be authorized but I am facing some issues. Here is the code for the endpoint:
[HttpGet("GetAllUsers")]
[Authorize]
public async Task<IActionResult> GetAllUsersAsync([FromQuery] UserParams userParams)
{
// Implementation here...
}
[HttpGet("GetAllUsers")]
[Authorize]
public async Task<IActionResult> GetAllUsersAsync([FromQuery] UserParams userParams)
{
// Implementation here...
}
Here is my JWT authentication setup:
builder.Services.AddAuthentication(authOptions =>
{
authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions =>
{
var key = builder.Configuration.GetValue<string>("JwtConfig:Key");
var keyBytes = Encoding.ASCII.GetBytes(key);

jwtOptions.SaveToken = true;
jwtOptions.RequireHttpsMetadata = false;
jwtOptions.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(keyBytes),
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuer = false,
ClockSkew = TimeSpan.Zero,

ValidIssuer = builder.Configuration["JwtConfig:Issuer"],
ValidAudience = builder.Configuration["JwtConfig:Audience"]
};
});
builder.Services.AddAuthentication(authOptions =>
{
authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions =>
{
var key = builder.Configuration.GetValue<string>("JwtConfig:Key");
var keyBytes = Encoding.ASCII.GetBytes(key);

jwtOptions.SaveToken = true;
jwtOptions.RequireHttpsMetadata = false;
jwtOptions.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(keyBytes),
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuer = false,
ClockSkew = TimeSpan.Zero,

ValidIssuer = builder.Configuration["JwtConfig:Issuer"],
ValidAudience = builder.Configuration["JwtConfig:Audience"]
};
});
The problem I'm encountering is when I try to access the GetAllUsersAsync endpoint with a valid token, I still get unauthorized responses. It seems the token isn't correctly validated or there's something wrong with my setup. Would appreciate any ideas or suggestions on what might be wrong. Thank you in advance.
2 Replies
_vegabyte_
_vegabyte_OP2y ago
To generate the JWT token, I use the following method:
private string GenerateJwtToken(Domain.Users user)
{
var key = _configuration.GetValue<string>("JwtConfig:Key");
var keyBytes = Encoding.ASCII.GetBytes(key);
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim("id", user.Id.ToString())
}),
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(keyBytes), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
private string GenerateJwtToken(Domain.Users user)
{
var key = _configuration.GetValue<string>("JwtConfig:Key");
var keyBytes = Encoding.ASCII.GetBytes(key);
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim("id", user.Id.ToString())
}),
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(keyBytes), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
artya
artya2y ago
You're missing an Audience claim You've also set ValidateIssuer to false, but you're still setting ValidIssuer 😛

Did you find this page helpful?