public static void AddJwtBearerPolicy(this IServiceCollection services, string issuer, string audience, string secret, TimeSpan expirationTimeSpan, bool isHttps = false, string defaultScheme = "ApiBearer", string policyName = "Api") { var keyByteArray = Encoding.UTF8.GetBytes(secret); var signingKey = new SymmetricSecurityKey(keyByteArray); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = issuer, //发行人 ValidAudience = audience, //订阅人 IssuerSigningKey = signingKey, ClockSkew = TimeSpan.Zero, //RequireExpirationTime = true, }; var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); //如果第三个参数,是ClaimTypes.Role,上面集合的每个元素的Name为角色名称,如果ClaimTypes.Name,即上面集合的每个元素的Name为用户名 var permissionRequirement = new PermissionRequirement( ClaimTypes.Role, issuer, audience, signingCredentials, expiration: expirationTimeSpan); services.AddSingleton(permissionRequirement); services.AddAuthorization(options => { options.AddPolicy(policyName, policy => policy.Requirements.Add(permissionRequirement)); }); services.AddTransient <IAuthorizationHandler, PermissionHandler>(); }
/// <summary> /// 获取基于JWT的Token /// </summary> /// <param name="username"></param> /// <returns></returns> public static dynamic BuildJwtToken(Claim[] claims, PermissionRequirement permissionRequirement) { var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: permissionRequirement.Issuer, audience: permissionRequirement.Audience, claims: claims, notBefore: now, expires: now.Add(permissionRequirement.Expiration), signingCredentials: permissionRequirement.SigningCredentials ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var responseJson = new { Status = true, access_token = encodedJwt, expires_in = permissionRequirement.Expiration.TotalMilliseconds, token_type = "Bearer" }; return(responseJson); }