Using the guide i posted in the comments. This isn't all you need - but i cant post code in comments. Needed long form.
You use claims to get the role into your token.
In your startup.cs
var secretKey = Configuration.GetSection("JWTSettings:SecretKey").Value;
var issuer = Configuration.GetSection("JWTSettings:Issuer").Value;
var audience = Configuration.GetSection("JWTSettings:Audience").Value;
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = issuer,
ValidateAudience = true,
ValidAudience = audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
};
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = tokenValidationParameters;
});
Then in your controller method that a user uses to "login" or issue a token.
var claims = new[] {
new Claim(ClaimTypes.Name, Credentials.Email),
new Claim(ClaimTypes.Role, Role) };
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
expires: DateTime.Now.AddYears(10),
signingCredentials: creds);
Then protect your method or controller with the role.
[Authorize(Roles = "Admin")]
[HttpGet]
Public IActionResult GrabStuff(){ }
[Authorize]
attributes on your controller, but you want to know how to read and use the token on the frontend part of your application? – UpQuark