C
C#13mo ago
Very Funny

Authorised endpoint returns 401

I am trying to add authentication to my app. I followed a recent tutorial almost verbatim, however my code is not working. I have login and register endpoints that are working fine.
c#
//--------
AuthController.cs
...
private string CreateToken(User user)
{
List<Claim> claims = new()
{
new (ClaimTypes.Name, user.UserName),
new (ClaimTypes.Role, "Admin")
};

SymmetricSecurityKey key = new(Encoding.UTF8.GetBytes(_configuration["JwtSettings:Key"]!));

SigningCredentials creds = new(key, SecurityAlgorithms.HmacSha256Signature);

JwtSecurityToken token = new(
claims: claims,
expires: DateTime.Now.AddDays(30),
signingCredentials: creds
);

return new JwtSecurityTokenHandler().WriteToken(token);
}
//--------
Program.cs
...
services.AddAuthentication().AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateAudience = false,
ValidateIssuer = false,

IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["JwtSettings:Key"]!))
};
});
...
//-------
WeatherForecastController.cs
...
[HttpGet]
[Authorize(Roles = "Admin")]
public IEnumerable<WeatherForecast> Get() { ... }
c#
//--------
AuthController.cs
...
private string CreateToken(User user)
{
List<Claim> claims = new()
{
new (ClaimTypes.Name, user.UserName),
new (ClaimTypes.Role, "Admin")
};

SymmetricSecurityKey key = new(Encoding.UTF8.GetBytes(_configuration["JwtSettings:Key"]!));

SigningCredentials creds = new(key, SecurityAlgorithms.HmacSha256Signature);

JwtSecurityToken token = new(
claims: claims,
expires: DateTime.Now.AddDays(30),
signingCredentials: creds
);

return new JwtSecurityTokenHandler().WriteToken(token);
}
//--------
Program.cs
...
services.AddAuthentication().AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateAudience = false,
ValidateIssuer = false,

IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["JwtSettings:Key"]!))
};
});
...
//-------
WeatherForecastController.cs
...
[HttpGet]
[Authorize(Roles = "Admin")]
public IEnumerable<WeatherForecast> Get() { ... }
1 Reply
Very Funny
Very FunnyOP13mo ago
Ok, It works via postman but not swagger. Any idea why?
Want results from more Discord servers?
Add your server