private async Task <JwtToken> GenerateJwtTokenAsync(JwtSection section, AuthUser user) { var role = (await userManager.GetRolesAsync(user)).Single(); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.Id), new Claim("roles", role) }; var key = section.GetSecurityKey(); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expires = DateTime.UtcNow.AddMinutes(section.ExpireMinutes); var token = new JwtSecurityToken( section.Issuer, section.Issuer, claims, expires: expires, signingCredentials: credentials ); return(new JwtToken { Token = new JwtSecurityTokenHandler().WriteToken(token), ExpirationDateTimeUtc = expires }); }
public static void AddShelterAuthentication(this IServiceCollection services, JwtSection section) { services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidAudience = section.Issuer, ValidIssuer = section.Issuer, IssuerSigningKey = section.GetSecurityKey(), ClockSkew = TimeSpan.Zero }; }); }