public static class JwtAuthenticationServiceCollectionExtension
{
public static IServiceCollection JwtAuthentication(this IServiceCollection services) {
if (services == null) throw new Exception("services不能为空对象");
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options=> {
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role,
//Token颁发机构
ValidIssuer = ConfigHelper.GetKey(AppsettingsKey.JwtIssuer),
//颁发给谁
ValidAudience = ConfigHelper.GetKey(AppsettingsKey.JwtAudience),
//这里的key要进行加密
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AccessTokenConst.AliPaySecret1)),
//// 允许的服务器时间偏移量
//ClockSkew = TimeSpan.FromSeconds(10),
//// 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
// ValidateLifetime = true
};
//options.Events = new JwtBearerEvents
//{
// //此处为权限验证失败后触发的事件
// OnChallenge = context =>
// {
// //此处代码为终止.Net Core默认的返回类型和数据结果,这个很重要哦,必须
// context.HandleResponse();
// //自定义自己想要返回的数据结果,我这里要返回的是Json对象,通过引用Newtonsoft.Json库进行转换
// var payload = "{\"Success\":false,\"Msg\":\"很抱歉,您无权访问该接口\",\"StatusCode\":401}";
// //自定义返回的数据类型
// context.Response.ContentType = "application/json";
// //自定义返回状态码,默认为401 我这里改成 200
// context.Response.StatusCode =200;
// //context.Response.StatusCode = StatusCodes.Status401Unauthorized;
// //输出Json数据结果
// context.Response.WriteAsync(payload);
// return Task.FromResult(0);
// }
//};
});
/***********************************TokenValidationParameters的参数默认值***********************************/
// RequireSignedTokens = true,
// SaveSigninToken = false,
// ValidateActor = false,
// 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
// ValidateAudience = true,
// ValidateIssuer = true,
// ValidateIssuerSigningKey = false,
// 是否要求Token的Claims中必须包含Expires
// RequireExpirationTime = true,
// 允许的服务器时间偏移量
// ClockSkew = TimeSpan.FromSeconds(300),
// 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
// ValidateLifetime = true
return services;
}
}
public static JwtResult WriteJwtToken(JwtModel model, double expiresTime=2*60*60) {
JwtResult jwtResult = new JwtResult();
string Audience = ConfigHelper.GetKey(AppsettingsKey.JwtAudience);
string Issuer = ConfigHelper.GetKey(AppsettingsKey.JwtIssuer);
if (string.IsNullOrWhiteSpace(Audience)) {
jwtResult.success = false;
jwtResult.msg = "必须指定jwt使用者";
return jwtResult;
}
if (string.IsNullOrWhiteSpace(Issuer))
{
jwtResult.success = false;
jwtResult.msg = "必须指定jwt颁发者";
return jwtResult;
}
var tokenHandler = new JwtSecurityTokenHandler();
//
var key = Encoding.UTF8.GetBytes(AccessTokenConst.AliPaySecret1);
var authTime = DateTime.Now;//授权时间
var expiresAt = authTime.AddSeconds(expiresTime);//过期时间
List<Claim> claims = new List<Claim>();
claims.Add(new Claim("Audience", Audience));
claims.Add(new Claim("Issuer", Issuer));
if (!string.IsNullOrWhiteSpace(model.ID)) claims.Add(new Claim("Id", model.ID));
if (!string.IsNullOrWhiteSpace(model.Name)) claims.Add(new Claim("Name", model.Name));
//if (!string.IsNullOrWhiteSpace(model.PlatformID)) claims.Add(new Claim("PlatformID", model.PlatformID));
//if (!string.IsNullOrWhiteSpace(model.StationID)) claims.Add(new Claim("StationID", model.StationID));
//if (!string.IsNullOrWhiteSpace(model.Roles)) claims.Add(new Claim("Roles", model.Roles));
//if (!string.IsNullOrWhiteSpace(model.Actions)) claims.Add(new Claim("Actions", model.Actions));
var tokenDescripor = new SecurityTokenDescriptor {
Subject=new ClaimsIdentity (claims),
Expires= expiresAt,
//签名证书
SigningCredentials= new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
SecurityToken token = tokenHandler.CreateToken(tokenDescripor);
string tokenString = tokenHandler.WriteToken(token);
jwtResult.success = true;
jwtResult.access_token = tokenString;
jwtResult.profile = model;
return jwtResult;
}
访问401
求问,解决了吗