在.NET Core中想给API进行安全认证,现在最常用的就是Jwt了,简单记录下JWT的使用方法。
一、首先在appsettings.json里写基本配置,参数如下
"JwtSecurity": { "Issuer": "", // 颁发者 "Audience": "", // 接收者 "TokenExpires": 7200, // 过期时间,秒为单位 "SecurityKey": "hello world" // 密钥 },
二、在Setup里加入限制
#region JWT验证 var jwtSecurity = Configuration.GetSection("JwtSecurity"); var key = jwtSecurity.GetValue<string>("SecurityKey"); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.IncludeErrorDetails = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, RequireExpirationTime = true, ClockSkew = TimeSpan.FromSeconds(0), }; x.Events = new JwtBearerEvents() { OnChallenge = new Func<JwtBearerChallengeContext, System.Threading.Tasks.Task>(async target => { target.HandleResponse(); target.Response.ContentType = "application/json"; target.Response.StatusCode = StatusCodes.Status401Unauthorized; string result = Newtonsoft.Json.JsonConvert.SerializeObject(new { state = ResultType.TokenOver, message = "授权失败" }); await target.Response.WriteAsync(result); }), }; }); #endregion
三、获取token
async Task<object> GetToken(UserInfo user) { var tokenHandler = new JwtSecurityTokenHandler(); var jwtSecurity = configuration.GetSection("JwtSecurity"); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecurity.GetValue<string>("SecurityKey"))); var nowTime = DateTime.Now; var tokenExpires = nowTime.Add(TimeSpan.FromSeconds(jwtSecurity.GetValue<int>("TokenExpires"))); var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName.ToString())); var tokenDescriptor = new SecurityTokenDescriptor { Subject = identity, Expires = tokenExpires, SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256) }; var token = tokenHandler.CreateToken(tokenDescriptor); return new { Code = ResultType.Success, Token = tokenHandler.WriteToken(token), TokenExpireTime = tokenExpires, }; }
在用户登录的时候,调用上面这个方法就可以获取token了,前端请求接口的时候需要携带token。