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() { ... }