/// <summary> /// 校验token是否正确 /// </summary> /// <param name="token"></param> /// <returns></returns> public virtual async Task <ClaimsPrincipal> ValidateTokenAsync(JwtTokenType jwtTokenType, string token, JwtOptions options = null) { if (options == null) { options = GetCurrentOptions(); } ClaimsPrincipal principal = _tokenHandler.ValidateToken(token, options.GetValidationParameters(), out _); string userId = null; if (options.EnabledSignalR) { userId = principal.Claims.FirstOrDefault(d => d.Type == nameof(TokenEntityBase.UserId)).Value; principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, userId) })); } if (options.Cache) { var clientType = principal.Claims.FirstOrDefault(d => d.Type == nameof(TokenEntityBase.ClientType)).Value; if (userId == null) { userId = principal.Claims.FirstOrDefault(d => d.Type == nameof(TokenEntityBase.UserId)).Value; } var tokenEntry = CacheEntryCollection.GetTokenEntry(jwtTokenType, clientType, userId, (int)options.AccessExpireMins * 60); var cacheToken = await _store.GetAsync <string>(tokenEntry); if (cacheToken.IsNullOrEmpty() || cacheToken != token) { throw new RyeException("Token is error"); } } return(principal); }
public virtual async Task <JsonWebToken> RefreshTokenAsync(string refreshToken, JwtOptions options = null) { Check.NotNull(refreshToken, nameof(refreshToken)); if (options == null) { options = GetCurrentOptions(); } TokenValidationParameters parameters = options.GetValidationParameters(); JwtSecurityToken jwtSecurityToken = _tokenHandler.ReadJwtToken(refreshToken); string clientId = jwtSecurityToken.Claims.FirstOrDefault(m => m.Type == "clientId")?.Value; if (clientId == null) { throw new RyeException("RefreshToken中不包含ClientId声明"); } ClaimsPrincipal principal = _tokenHandler.ValidateToken(refreshToken, parameters, out _); return(await GenerateTokenAsync(principal.Claims.ToList(), options)); }