Esempio n. 1
0
        /// <summary>
        /// 生成JWT Token
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="userName">用户名称</param>
        /// <param name="claims"></param>
        /// <param name="jwtTokenConfig"></param>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public async Task <JwtAuthInfo> GenerateTokens(long userId, string userName, Claim[] claims, DateTime dateTime)
        {
            var secret = Encoding.ASCII.GetBytes(jwtTokenConfig.SecretKey);
            var shouldAddAudienceClaim = string.IsNullOrWhiteSpace(claims?.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Aud)?.Value);
            var jwtToken = new JwtSecurityToken(
                jwtTokenConfig.Issuer,
                shouldAddAudienceClaim ? jwtTokenConfig.Audience : string.Empty,
                claims,
                expires: dateTime.AddMinutes(jwtTokenConfig.AccessTokenExpiration),
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(secret), SecurityAlgorithms.HmacSha256Signature));
            var accessToken = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            var entity = new RefreshTokenEntity
            {
                UserId   = userId,
                UserName = userName,
                Token    = GenerateRefreshToken(),
                ExpireAt = dateTime.AddMinutes(jwtTokenConfig.RefreshTokenExpiration)
            };
            //redisCacheService.SetEntryInHash(redisCacheHashId, refreshToken.TokenString, refreshToken);
            await tokenRepository.AddOrUpdate(entity);

            return(new JwtAuthInfo
            {
                AccessToken = accessToken,
                RefreshToken = MapperTo(entity)
            });
        }