コード例 #1
0
        public async Task <Tokens> GetRefreshTokenAsync(string refreshToken)
        {
            LinUser user = await _userRepository.GetUserAsync(r => r.RefreshToken == refreshToken);

            if (user.IsNull())
            {
                throw new LinCmsException("该refreshToken无效!");
            }

            if (DateTime.Compare(user.LastLoginTime, DateTime.Now) > new TimeSpan(30, 0, 0, 0).Ticks)
            {
                throw new LinCmsException("请重新登录", ErrorCode.RefreshTokenError);
            }

            List <Claim> claims = new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Email, user.Email ?? ""),
                new Claim(ClaimTypes.GivenName, user.Nickname ?? ""),
                new Claim(ClaimTypes.Name, user.Username ?? ""),
            };

            _logger.LogInformation($"用户{user.Username},JwtRefreshToken 刷新-登录成功,{JsonConvert.SerializeObject(claims)}");

            string token = _jsonWebTokenService.Encode(claims);

            refreshToken = GenerateToken();
            user.AddRefreshToken(refreshToken);
            await _userRepository.UpdateAsync(user);

            return(new Tokens(token, refreshToken));
        }
コード例 #2
0
        private async Task <Tokens> CreateTokenAsync(LinUser user)
        {
            List <Claim> claims = new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Email, user.Email ?? ""),
                new Claim(ClaimTypes.GivenName, user.Nickname ?? ""),
                new Claim(ClaimTypes.Name, user.Username ?? ""),
            };

            user.LinGroups?.ForEach(r =>
            {
                claims.Add(new Claim(ClaimTypes.Role, r.Name));
                claims.Add(new Claim(LinCmsClaimTypes.Groups, r.Id.ToString()));
            });

            string token = _jsonWebTokenService.Encode(claims);

            string refreshToken = GenerateToken();

            user.AddRefreshToken(refreshToken);
            await _userRepository.UpdateAsync(user);

            return(new Tokens(token, refreshToken));
        }
コード例 #3
0
        /// <summary>
        /// JWT登录
        /// </summary>
        /// <param name="loginInputDto"></param>
        /// <returns></returns>
        public async Task <Tokens> LoginAsync(LoginInputDto loginInputDto)
        {
            _logger.LogInformation("JwtLogin");

            LinUser user = await _userRepository.GetUserAsync(r => r.Username == loginInputDto.Username);

            if (user == null)
            {
                throw new LinCmsException("用户不存在", ErrorCode.NotFound);
            }

            bool valid = await _userIdentityService.VerifyUserPasswordAsync(user.Id, loginInputDto.Password);

            if (!valid)
            {
                throw new LinCmsException("请输入正确密码", ErrorCode.ParameterError);
            }


            List <Claim> claims = new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Email, user.Email ?? ""),
                new Claim(ClaimTypes.GivenName, user.Nickname ?? ""),
                new Claim(ClaimTypes.Name, user.Username ?? "")
            };

            user.LinGroups?.ForEach(r =>
            {
                claims.Add(new Claim(ClaimTypes.Role, r.Name));
                claims.Add(new Claim(LinCmsClaimTypes.Groups, r.Id.ToString()));
            });

            _logger.LogInformation($"用户{loginInputDto.Username},登录成功,{JsonConvert.SerializeObject(claims)}");

            string token = _jsonWebTokenService.Encode(claims);

            var refreshToken = GenerateToken();

            user.AddRefreshToken(refreshToken);
            await _userRepository.UpdateAsync(user);

            return(new Tokens(token, refreshToken));
        }
コード例 #4
0
        public async Task <IActionResult> Home(string provider, string redirectUrl = "")
        {
            if (string.IsNullOrWhiteSpace(provider))
            {
                return(BadRequest());
            }

            if (!await HttpContext.IsProviderSupportedAsync(provider))
            {
                return(BadRequest());
            }

            AuthenticateResult authenticateResult = await HttpContext.AuthenticateAsync(provider);

            if (!authenticateResult.Succeeded)
            {
                return(Redirect(redirectUrl));
            }
            var openIdClaim = authenticateResult.Principal?.FindFirst(ClaimTypes.NameIdentifier);

            if (openIdClaim == null || string.IsNullOrWhiteSpace(openIdClaim.Value))
            {
                return(Redirect(redirectUrl));
            }

            List <string> supportProviders = new List <string> {
                LinUserIdentity.Gitee, LinUserIdentity.GitHub, LinUserIdentity.QQ,
            };

            if (!supportProviders.Contains(provider))
            {
                _logger.LogError($"未知的privoder:{provider},redirectUrl:{redirectUrl}");
                throw new LinCmsException($"未知的privoder:{provider}!");
            }

            IOAuth2Service oAuth2Service = _componentContext.ResolveNamed <IOAuth2Service>(provider);

            long id = await oAuth2Service.SaveUserAsync(authenticateResult.Principal, openIdClaim.Value);

            List <Claim> authClaims = authenticateResult.Principal.Claims.ToList();

            LinUser user = await _userRepository.Select.IncludeMany(r => r.LinGroups)
                           .WhereCascade(r => r.IsDeleted == false).Where(r => r.Id == id).FirstAsync();

            if (user == null)
            {
                throw new LinCmsException("第三方登录失败!");
            }
            List <Claim> claims = new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Email, user.Email ?? ""),
                new Claim(ClaimTypes.GivenName, user.Nickname ?? ""),
                new Claim(ClaimTypes.Name, user.Username ?? ""),
            };

            user.LinGroups?.ForEach(r =>
            {
                claims.Add(new Claim(LinCmsClaimTypes.Groups, r.Id.ToString()));
            });

            //claims.AddRange(authClaims);
            string token = _jsonWebTokenService.Encode(claims);

            // 生成刷新token
            user.AddRefreshToken();
            await _userRepository.UpdateAsync(user);

            return(Redirect($"{redirectUrl}#login-result?token={token}"));
        }