예제 #1
0
        public async Task <RefreshTokenViewModel> GetRefreshToken(int viewModelId)
        {
            var result = await _refreshTokenRepository.GetAllMatchingAsync(rt => rt.UserId == viewModelId);

            if (result.Any())
            {
                return(_refreshMapper.GetViewModel(result.FirstOrDefault()));
            }

            var newRefreshToken = GetNewRefreshToken(viewModelId);
            await _refreshTokenRepository.AddAsync(newRefreshToken);

            return(_refreshMapper.GetViewModel(newRefreshToken));
        }
예제 #2
0
        public async Task <JsonWebToken> SignInAsync(string email, string password)
        {
            var user = await _userRepository.GetAsync(email);

            if (user == null || !user.ValidatePassword(password, _passwordHasher))
            {
                throw new ToolBoxException(Codes.InvalidCredentials,
                                           "Invalid credentials.");
            }
            var refreshToken = new RefreshToken();

            refreshToken.SetToken(user, _passwordHasher);
            var claims = await _claimsProvider.GetAsync(user);

            var jwt = _jwtHandler.CreateToken(user.Id.ToString(), null, claims);

            jwt.RefreshToken = refreshToken.Token;

            if (user.RefreshToken != null)
            {
                user.RefreshToken.Token = refreshToken.Token;
                user.RefreshToken.SetUpdatedDate();
            }
            else
            {
                await _refreshTokenRepository.AddAsync(refreshToken);

                user.RefreshToken   = refreshToken;
                user.RefreshTokenId = refreshToken.Id;
            }
            await _userRepository.UpdateAsync(user);

            return(jwt);
        }
예제 #3
0
        public async Task <JsonWebToken> SignInAsync(string name, string password)
        {
            var user = await _userRepository.GetAsync(name);

            if (user == null || !user.ValidatePassword(password, _passwordHasher))
            {
                throw new Exception("用户名或密码错误.");
            }

            var refreshToken = new RefreshToken(user, _passwordHasher);
            var jwt          = _jwtHandler.CreateToken(user.Id.ToString("N"), user.Role,
                                                       new Dictionary <string, string>()
            {
                ["Company"] = "SN"
            });

            jwt.RefreshToken = refreshToken.Token;
            await _refreshTokenRepository.AddAsync(refreshToken);

            //将用户添加到redis
            var userValue = System.Text.Encoding.Default.GetBytes(user.Name);
            await _distributedCache.SetAsync(user.Id.ToString(), userValue);

            _snRabbitMqClient.Publish(JsonConvert.SerializeObject(new SignedIn(user.Id)));
            return(jwt);
        }
예제 #4
0
        private async Task <AuthenticationResult> GenerateAuthenticationResultForUserAsync(User user)
        {
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Email, user.Email),
                    new Claim("id", user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.Add(_jwtSettings.TokenLifeTime),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token        = tokenHandler.CreateToken(tokenDescriptor);
            var refreshToken = new RefreshToken
            {
                JwtId        = token.Id,
                UserId       = user.Id,
                ExpiredOnUtc = DateTime.UtcNow.AddDays(30),
                Token        = Guid.NewGuid().ToString()
            };
            await _refreshTokenRepository.AddAsync(refreshToken);

            await _unitOfWork.SaveChangesAsync();

            return(new AuthenticationResult
            {
                Token = tokenHandler.WriteToken(token),
                RefreshToken = refreshToken.Token,
                IsSuccess = true
            });
        }
예제 #5
0
        public async Task <AuthDto> UseAsync(string refreshToken)
        {
            var token = await _refreshTokenRepository.GetAsync(refreshToken);

            if (token is null)
            {
                throw new InvalidRefreshTokenException();
            }

            token.Use(_dateTimeProvider.Now);
            var user = await _userRepository.GetAsync(token.UserId);

            if (user is null)
            {
                throw new UserNotFoundException(token.UserId);
            }

            var claims = user.Permissions.Any()
                ? new Dictionary <string, IEnumerable <string> >
            {
                ["permissions"] = user.Permissions
            }
                : null;

            var auth            = _jwtProvider.Create(token.UserId, user.Name, user.Role, claims: claims);
            var newRefreshToken = _refreshTokenFactory.Create(user.Id);
            await _refreshTokenRepository.AddAsync(newRefreshToken);

            await _refreshTokenRepository.UpdateAsync(token);

            auth.RefreshToken = newRefreshToken.Token;

            return(auth);
        }
예제 #6
0
        private async Task <string> CreateRefreshTokenAsync(int userId)
        {
            var refreshToken = _refreshTokenFactory.Create(userId);
            await _refreshTokenRepository.AddAsync(refreshToken);

            return(refreshToken.Token);
        }
예제 #7
0
        public async Task <JsonWebToken> HandleAsync(SignInQuery query)
        {
            var user = await _userRepository.GetAsync(query.Email);

            if (user == null || !user.ValidatePassword(query.Password, _passwordHasher))
            {
                throw new DomainException(Codes.InvalidCredentials, MessagesCode.InvalidCredentials);
            }

            var rolesName = user.UserRoles != null?user.UserRoles.Select(x => x.Role.RoleName).ToList() : new List <string>();

            var refreshToken = new RefreshToken(user, _passwordHasher);

            var claim = new Dictionary <string, string>()
            {
                { CoreConstants.OnUserIdClaimType, user.Id.ToString() },
                { CoreConstants.RoleIdClaimType, string.Join(",", rolesName) }
            };

            var jwt = _jwtHandler.CreateToken(user.Id.ToString("N"), rolesName, claim);

            jwt.RefreshToken = refreshToken.Token;

            await _refreshTokenRepository.AddAsync(refreshToken);

            return(jwt);
        }
예제 #8
0
        public async Task <string> CreateAsync(Guid userId)
        {
            var token        = _rng.Generate(30, true);
            var refreshToken = new RefreshToken(new AggregateId(), userId, token, DateTime.UtcNow);
            await _refreshTokenRepository.AddAsync(refreshToken);

            return(token);
        }
        private async Task <string> CreateRefreshTokenAsync(Guid userId)
        {
            var token        = _rng.Generate(30, true);
            var refreshToken = new RefreshToken(new AggregateId(), userId, token, _clock.Current());
            await _refreshTokenRepository.AddAsync(refreshToken);

            return(token);
        }
예제 #10
0
        public async Task <string> CreateRefreshToken(string email)
        {
            using var randomGenerator = RandomNumberGenerator.Create();
            byte[] tokenBytes = new byte[256 / 8];
            randomGenerator.GetBytes(tokenBytes);
            var token = Convert.ToBase64String(tokenBytes);
            await _repository.AddAsync(new RefreshToken(token, email));

            return(token);
        }
        public async Task AddAsync(Guid userId)
        {
            var user = await _userRepository.GetAsync(userId);

            if (user == null)
            {
                throw new VirtualMarketException(Codes.UserNotFound,
                                                 $"User: '******' was not found.");
            }
            await _refreshTokenRepository.AddAsync(new RefreshToken(user, _passwordHasher));
        }
예제 #12
0
        public async Task AddAsync(Guid userId)
        {
            var user = await _userRepository.GetAsync(userId);

            if (user is null)
            {
                throw new ServiceException(ExceptionCode.UserNotExists,
                                           $"User: '******' was not found.");
            }

            await _refreshTokenRepository.AddAsync(new RefreshToken(user, _passwordHasher));
        }
예제 #13
0
        public async Task <string> CreateAsync(Guid userId)
        {
            var token        = _rng.Generate(30, true);
            var now          = _clock.CurrentDate();
            var expires      = now.Add(_options.ExpiryRefreshToken);
            var refreshToken = new RefreshToken(Guid.NewGuid(), userId, token, DateTime.UtcNow, expires);
            await _refreshTokenRepository.DeleteAsync(userId);

            await _refreshTokenRepository.AddAsync(refreshToken);

            return(token);
        }
예제 #14
0
        public async Task <RefreshTokenModel> CreateAsync(RefreshTokenModel token)
        {
            var tokenEntity = new RefreshTokenEntity
            {
                Token  = token.Token,
                UserId = token.UserId
            };

            var createdToken = await _RefreshTokenRepository.AddAsync(tokenEntity);

            return(ConvertEntityToModel(createdToken));
        }
예제 #15
0
        public async Task <string> GenerateRefreshTokenAsync(int userId)
        {
            string token = new RefreshTokenGenerator().Generate();

            await _refreshTokenRepository.AddAsync(new RefreshToken
            {
                Id      = token,
                Created = DateTime.UtcNow,
                UserId  = userId
            });

            await _storage.SaveAsync();

            return(token);
        }
예제 #16
0
        public async Task AddAsync(Guid userId)
        {
            var user = await _userRepository.GetAsync(userId);

            if (user == null)
            {
                throw new ToolBoxException(Codes.UserNotFound,
                                           $"User: '******' was not found.");
            }
            var refreshToken = new RefreshToken();

            refreshToken.SetToken(user, _passwordHasher);

            await _refreshTokenRepository.AddAsync(refreshToken);
        }
        public async Task <JsonWebToken> SignInAsync(string email, string password)
        {
            var user = await _userRepository.GetAsync(email);

            if (user == null || !user.ValidatePassword(password, _passwordHasher))
            {
                throw new CoursesManagementException(ExceptionCodes.InvalidCredentials,
                                                     "Invalid credentials.");
            }
            var refreshToken = new RefreshToken(user, _passwordHasher);
            var jwt          = _jwtHandler.CreateToken(user.Id.ToString("N"), user.Role, null);

            jwt.RefreshToken = refreshToken.Token;
            await _refreshTokenRepository.AddAsync(refreshToken);

            return(jwt);
        }
        private async Task <RefreshToken> AttachRefreshToken(long accountId)
        {
            string token = _tokenFactory.GenerateEncodedRefreshToken();

            DateTime dateTimeNow = DateTime.Now;

            var refreshToken = new RefreshToken
            {
                AccountId  = accountId,
                Token      = token,
                IssuedUtc  = dateTimeNow,
                ExpiresUtc = dateTimeNow.AddDays(14)
            };

            await _refreshTokenRepository.AddAsync(refreshToken);

            return(refreshToken);
        }
예제 #19
0
        public async Task <JsonWebToken> SignInAsync(string email, string password)
        {
            var user = await _userRepository.GetByEmailAsync(email);

            if (user == null || !user.ValidatePassword(password, _passwordHasher))
            {
                throw new ServiceException(ErrorCodes.InvalidCredentials,
                                           "Invalid credentials.");
            }
            var refreshToken = new RefreshToken(user, _passwordHasher);
            var jwt          = _jwtHandler.CreateToken(user.SerialNumber, user.Role);

            jwt.RefreshToken = refreshToken.Token;
            await _refreshTokenRepository.AddAsync(refreshToken);

            await _unitOfWork.SaveChangesAsync();

            return(jwt);
        }
예제 #20
0
        public async Task <JsonWebToken> SignInAsync(string email, string password)
        {
            var user = await _userRepository.GetAsync(email);

            if (user == null || !user.ValidatePassword(password, _passwordHasher))
            {
                throw new MicroSException(Codes.InvalidCredentials, "Invalid credentials.");
            }
            var refreshToken = new dto.RefreshToken(user, _passwordHasher);
            var claims       = await _claimsProvider.GetAsync(user.Id);

            var jwt = _jwtHandler.CreateToken(user.Id.ToString("N"), user.Role, claims);

            jwt.RefreshToken = refreshToken.Token;
            await _refreshTokenRepository.AddAsync(refreshToken);

            await _busPublisher.PublishAsync(new SignedIn(user.Id), CorrelationContext.Empty);

            return(jwt);
        }
예제 #21
0
        public async Task <JsonWebToken> SignInAsync(string username, string password)
        {
            var user = await _userRepository.GetAsync(username);

            if (user == null || !user.VerifyHashedPassword(password, _passwordHasher))
            {
                throw new S3Exception(ExceptionCodes.InvalidCredentials,
                                      "Invalid credentials.");
            }
            var refreshToken = new RefreshToken(user, _passwordHasher);
            var claims       = await _claimsProvider.GetAsync(user);

            //var claims = await _claimsProvider.GetAsync(user.Id);
            var jwt = _jwtHandler.CreateToken(user.Id.ToString("N"), user.Roles, claims);

            jwt.RefreshToken = refreshToken.Token;
            await _refreshTokenRepository.AddAsync(refreshToken);

            return(jwt);
        }
        public async Task <JsonWebToken> SignInAsync(string userName, string password, UserType?userType)
        {
            var user = await _userManager.FindByNameAsync(userName);

            if (user == null || !user.ValidatePassword(password, _passwordHasher))
            {
                throw new Exception("Invalid credentials.");
            }
            //user.LastLoginTime =
            await _signInManager.SignInAsync(user, false);

            var refreshToken = new RefreshToken(user, _passwordHasher);
            var claims       = await _userManager.GetClaimsAsync(user);

            var jwt = _jwtHandler.CreateToken(user.Id.ToString(), userType.ToString(), claims.ToDictionary(c => c.Type, c => c.Value));

            jwt.RefreshToken = refreshToken.Token;
            await _refreshTokenRepository.AddAsync(refreshToken);

            return(jwt);
        }
예제 #23
0
        // Refreshing token

        public async Task <JwtDto> UseAsync(string refreshToken)
        {
            var token = await _refreshTokenRepository.GetAsync(refreshToken);

            if (token is null)
            {
                throw new InvalidRefreshTokenException();
            }

            token.Use(_dateTimeProvider.Now);
            var user = await _userService.GetAsync(token.UserId);

            var jwt             = _jwtHandler.CreateToken(token.UserId, user.UserName, user.Role);
            var newRefreshToken = _refreshTokenFactory.Create(user.Id);
            await _refreshTokenRepository.AddAsync(newRefreshToken);

            await _refreshTokenRepository.UpdateAsync(token);

            jwt.RefreshToken = newRefreshToken.Token;

            return(jwt);
        }
예제 #24
0
        public async Task <JsonWebToken> LoginAsync(string email, string password)
        {
            var user = await _userRepository.GetAsync(email);

            if (user == null)
            {
                throw new HttpResponseException(StatusCodes.Status401Unauthorized, "Invalid credentials");
            }
            if (!user.ValidatePassword(password, _encrypter))
            {
                throw new HttpResponseException(StatusCodes.Status401Unauthorized, "Invalid credentials");
            }
            var jwt = _jwtHandler.Create(user.Id);
            await _refreshTokenRepository.AddAsync(new RefreshToken()
            {
                UserId  = user.Id,
                Token   = jwt.RefreshToken.Value,
                Expires = (new DateTime(1970, 1, 1)).AddSeconds(jwt.RefreshToken.Expires)
            });

            return(jwt);
        }
예제 #25
0
        public async Task <JwtDTO> Login(string login, string password)
        {
            var user = await _userRepository.GetAsync(login);

            if (user == null)
            {
                throw new NewException(NewCodes.UserNotFound);
            }
            var hash = _encrypter.GetHash(password, user.Salt);

            if (user.Password != hash)
            {
                throw new NewException(NewCodes.WrongCredentials);
            }
            var jwt          = _jwtHandler.CreateToken(user.Id);
            var refreshToken = await _refreshTokens.GetByUserIdAsync(user.Id);

            string token = "";

            if (refreshToken == null)
            {
                token = Guid.NewGuid().ToString()
                        .Replace("+", string.Empty)
                        .Replace("=", string.Empty)
                        .Replace("/", string.Empty);
                await _refreshTokens.AddAsync(new RefreshToken(user, token));
            }
            else
            {
                token = refreshToken.Token;
            }
            var jwtDto = new JwtDTO()
            {
                AccessToken = jwt.AccessToken, Expires = jwt.Expires, RefreshToken = token, UserId = jwt.UserId
            };

            return(jwtDto);
        }
 private async Task AddRefreshTokenAsync(Guid clientId, string refreshToken)
 {
     await _refreshTokenRepository.AddAsync(new ClientRefreshToken { ClientId = clientId, RefreshToken = refreshToken });
 }
예제 #27
0
        private async Task <AuthenticationResult> GenerateAuthenticationResultForUserAsync(IdentityUser user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(jwtSettings.Secret);

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim("id", user.Id)
            };

            var userClaims = await userManager.GetClaimsAsync(user).ConfigureAwait(false);

            claims.AddRange(userClaims);

            var userRoles = await userManager.GetRolesAsync(user);

            foreach (var userRole in userRoles)
            {
                claims.Add(new Claim(ClaimTypes.Role, userRole));
                var role = await roleManager.FindByNameAsync(userRole).ConfigureAwait(false);

                if (role == null)
                {
                    continue;
                }
                var roleClaims = await roleManager.GetClaimsAsync(role).ConfigureAwait(false);

                foreach (var roleClaim in roleClaims)
                {
                    if (claims.Contains(roleClaim))
                    {
                        continue;
                    }

                    claims.Add(roleClaim);
                }
            }

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.Add(jwtSettings.TokenLifetime),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                            SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var refreshToken = new RefreshToken
            {
                JwtId        = token.Id,
                UserId       = user.Id,
                CreationDate = DateTime.UtcNow,
                ExpiryDate   = DateTime.UtcNow.AddMonths(6)
            };

            await refreshTokenRepository.AddAsync(refreshToken).ConfigureAwait(false);

            await refreshTokenRepository.SaveAsync().ConfigureAwait(false);

            return(new AuthenticationResult
            {
                Success = true,
                Token = tokenHandler.WriteToken(token),
                RefreshToken = refreshToken.Token
            });
        }