public JwtLoginResult LogIn(string userName, IEnumerable <string> roles, JwtAuthenticationOptions options) { var handler = new JwtSecurityTokenHandler(); var claims = new List <Claim> { new Claim(ClaimTypes.Name, userName) }; claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r))); var now = DateTimeOffset.Now; var expires = now + options.AccessTokenExpireTime; var descriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Issuer = Options.Issuer, Audience = Options.Audience, IssuedAt = now.UtcDateTime, NotBefore = now.UtcDateTime, Expires = expires?.UtcDateTime, SigningCredentials = new SigningCredentials(TokenValidationParameters.IssuerSigningKey, options.SigningAlgorithm) }; var token = handler.CreateToken(descriptor); return(new JwtLoginResult(userName, handler.WriteToken(token), now, expires)); }
public JwtAuthenticator(TokenValidationParameters tokenValidationParameters, JwtAuthenticationOptions options) { TokenValidationParameters = tokenValidationParameters; Options = options; }
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, JwtAuthenticationOptions options, TokenValidationParameters parameters) { return(services.AddJwtAuthentication(options, jwt => { jwt.TokenValidationParameters = parameters; })); }
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, JwtAuthenticationOptions options) { var key = System.Text.Encoding.ASCII.GetBytes(options.Secret); var parameters = new TokenValidationParameters { ValidIssuer = options.Issuer, ValidAudience = options.Audience, ValidateIssuer = options.Issuer != null, ValidateAudience = options.Audience != null, ValidateLifetime = options.AccessTokenExpireTime != null, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key) }; return(services.AddJwtAuthentication(options, parameters)); }
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, JwtAuthenticationOptions options, Action <JwtBearerOptions> configureOptions) { var optionsInstance = new JwtBearerOptions(); configureOptions(optionsInstance); var jwtService = new JwtAuthenticator(optionsInstance.TokenValidationParameters, options); services.AddAuthentication().AddJwtBearer(configureOptions); return(services.AddSingleton <IJwtAuthenticator>(jwtService)); }