/// <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); }
private async Task <JsonWebToken> GenerateTokenAsync(List <Claim> claims, JwtOptions options) { claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, $"{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}")); claims.Add(new Claim(JwtRegisteredClaimNames.Exp, $"{DateTimeOffset.UtcNow.AddMinutes(options.AccessExpireMins).ToUnixTimeSeconds()}")); // AccessToken var(accessToken, accessExpires) = CreateTokenCore(claims, options, JwtTokenType.AccessToken); // RefreshToken var(refreshToken, refreshExpires) = CreateTokenCore(claims, options, JwtTokenType.RefreshToken); if (options.Cache) { var clientType = claims.FirstOrDefault(d => d.Type == nameof(TokenEntityBase.ClientType)).Value; var userId = claims.FirstOrDefault(d => d.Type == nameof(TokenEntityBase.UserId)).Value; var tokenEntry = CacheEntryCollection.GetTokenEntry(JwtTokenType.AccessToken, clientType, userId, (int)options.AccessExpireMins * 60); await _store.SetAsync <string>(tokenEntry, accessToken); tokenEntry = CacheEntryCollection.GetTokenEntry(JwtTokenType.RefreshToken, clientType, userId, (int)options.AccessExpireMins * 60); await _store.SetAsync <string>(tokenEntry, accessToken); } return(new JsonWebToken() { AccessToken = accessToken, RefreshToken = refreshToken, AccessExpires = accessExpires.ToUniversalTime().Ticks, RefreshExpires = refreshExpires.ToUniversalTime().Ticks//expires.ToJsGetTime().ParseByLong() }); }
/// <summary> /// 设置验证码到缓存中 /// </summary> public virtual async Task <string> SetCodeAsync(string code) { var id = Guid.NewGuid().ToString("N"); var entry = CacheEntryCollection.GetVerifyCodeEntry(id, _options.VerfiyCodeExpire); await _store.SetAsync(entry, code); return(id); }
public virtual async Task DeleteTokenAsync(string userId, string clientType) { var tokenEntry = CacheEntryCollection.GetTokenEntry(JwtTokenType.AccessToken, clientType, userId); await _store.RemoveAsync(tokenEntry.Key); tokenEntry = CacheEntryCollection.GetTokenEntry(JwtTokenType.RefreshToken, clientType, userId); await _store.RemoveAsync(tokenEntry.Key); }
public override async Task <(bool, JsonResult)> AuthorizeAsync(HttpContext httpContext, TokenValidResult validResult) { var url = httpContext.Request.Path.Value.ToLower(); var roleIds = httpContext.User.Claims.FirstOrDefault(c => c.Type.Equals(nameof(PermissionTokenEntity.RoleIds), StringComparison.InvariantCultureIgnoreCase))?.Value; var secutiryPermissionService = httpContext.RequestServices.GetService <IPermissionService>(); if (secutiryPermissionService == null) { return(true, null); } if (roleIds.IsNullOrEmpty()) { return(false, Provider.CreatePermissionNotAllowResponse(httpContext)); } var userId = httpContext.User?.Claims.FirstOrDefault(c => c.Type.Equals(nameof(PermissionTokenEntity.UserId), StringComparison.InvariantCultureIgnoreCase))?.Value; if (userId.IsNullOrEmpty()) { return(false, Provider.CreatePermissionNotAllowResponse(httpContext)); } var store = httpContext.RequestServices.GetRequiredService <ICacheStore>(); var entry = CacheEntryCollection.GetPermissionEntry(userId); IEnumerable <string> permissionList = await store.GetAsync <IEnumerable <string> >(entry); if (permissionList == null || !permissionList.Any()) { permissionList = await secutiryPermissionService.GetPermissionCodeAsync(roleIds); if (permissionList != null && permissionList.Any()) { await store.SetAsync(entry, permissionList); } } var area = httpContext.GetRouteValue("area")?.ToString(); var controller = httpContext.GetRouteValue("controller")?.ToString(); var action = httpContext.GetRouteValue("action")?.ToString(); var authCode = AuthCode ?? (area != null ? $"{area}_{controller}.{action}" : $"{controller}.{action}"); if (!permissionList.Any(d => string.Equals(d, authCode, System.StringComparison.InvariantCultureIgnoreCase))) { return(false, Provider.CreatePermissionNotAllowResponse(httpContext)); } return(true, null); }
/// <summary> /// 校验验证码有效性 /// </summary> /// <param name="code">要校验的验证码</param> /// <param name="id">验证码编号</param> /// <param name="removeIfSuccess">验证成功时是否移除</param> /// <returns></returns> public virtual async Task <bool> CheckCodeAsync(string id, string code, bool removeIfSuccess = true) { if (string.IsNullOrEmpty(code)) { return(false); } var entry = CacheEntryCollection.GetVerifyCodeEntry(id); var validCode = _store.Get <string>(entry); bool flag = code.Equals(validCode, StringComparison.InvariantCultureIgnoreCase); if (removeIfSuccess && flag) { await _store.RemoveAsync(entry.Key); } return(flag); }