public virtual async Task <TokenCreateResult> RefreshAsync(string refreshToken, string scheme = null) { await InitializeAsync(scheme); var token = await _tokenStore.GetAsync(refreshToken, _innerScheme); if (token == null || token.Type != TokenType.Refresh) { return(TokenCreateResult.Failed("invalid refresh_token")); } if (!token.IsValid) { return(TokenCreateResult.Failed($"The refresh_token expired at '{token.Expiration.LocalDateTime.ToString(CultureInfo.InvariantCulture)}'")); } var claims = await GetUserClaimsAsync(token.UserId); var result = CreateToken(token.UserId, claims, _innerScheme); await _tokenStore.RemoveAsync(refreshToken, _innerScheme); if (_options.AllowMultiTokenActive && _options.KeepTokenValidTimeSpanOnRefresh != null) { var tokenList = await _tokenStore.GetListAsync(token.UserId, _innerScheme, TokenType.Bearer); var validTokenList = tokenList .Where(a => a.Expiration - DateTime.Now > _options.KeepTokenValidTimeSpanOnRefresh).ToList(); validTokenList.ForEach(a => a.Expiration = DateTime.Now + _options.KeepTokenValidTimeSpanOnRefresh.Value); foreach (var item in validTokenList) { await _cacheService.SetAsync(item); } await _tokenStore.UpdateListAsync(validTokenList); } await RemoveAllOldTokenAsync(token.UserId, _innerScheme); await _tokenStore.StoreAsync(new List <TokenModel>() { result.Bearer, result.Refresh }); if (_options.UseCache) { await _cacheService.SetAsync(result.Bearer); } return(result); }
public virtual async Task <ClaimsPrincipal> ValidateTokenAsync(ApiTokenOptions options, [NotNull] string token, string schemeName) { TokenModel tokenModel = null; //Get from cache if (options.UseCache) { var tokenModelCache = await _cacheService.GetAsync(token, schemeName); if (tokenModelCache != null) { if (tokenModelCache.Available) { tokenModel = tokenModelCache.Token; } else { throw new TokenInvalidException("matching token could not be found from cache"); } } } //If cache return null, then get from db if (tokenModel == null) { var queryTokenModel = await _store.GetAsync(token, schemeName); if (queryTokenModel != null && queryTokenModel.IsValid) { tokenModel = queryTokenModel; } //set cache if (tokenModel != null && options.UseCache) { await _cacheService.SetAsync(tokenModel); } } if (tokenModel == null) { if (options.UseCache) { await _cacheService.SetNullAsync(token, schemeName); } throw new TokenInvalidException("matching token could not be found"); } //Check expiration if (!tokenModel.IsValid) { throw new TokenExpiredException("Token expired at " + tokenModel.Expiration, tokenModel.Expiration.DateTime); } //Generate ClaimsPrincipal var claims = tokenModel.Claims; var result = new ClaimsPrincipal(); result.AddIdentity(new ClaimsIdentity(claims, schemeName, options.NameClaimType, options.RoleClaimType)); return(result); }