C#C
C#3y 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() { ... }
Was this page helpful?