Exemplo n.º 1
0
        /// <summary>
        /// Generate Access Token and Refresh Token
        /// </summary>
        /// <param name="token"></param>
        /// <returns>return TokenDto with code 200</returns>
        public async Task <TokenDto> GenerateRefreshTokenAsync(TokenClaimsDto token)
        {
            TokenDto tokenDto = new TokenDto();
            var      user     = await userRepository.FindByIdDetailsAsync(token.UserId);

            tokenDto.AccessToken  = tokenGeneratorService.GenerateToken(user);
            tokenDto.RefreshToken = tokenGeneratorService.RefreshGenerateToken();
            tokenDto.Code         = 200;
            return(tokenDto);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Check date of end refresh token
        /// delete old refresh token
        /// </summary>
        /// <param name="refresh"></param>
        /// <returns>return TokenClaimsDto with status checkRefreshToken true
        /// or with status checkRefreshToken false</returns>
        public async Task <TokenClaimsDto> CheckAccessRefreshTokenAsync(string refresh)
        {
            TokenClaimsDto token = new TokenClaimsDto();
            var            check = await refreshRepository.FindByRefreshTokenAsync(refresh);

            if (check == null || check.DateOfEnd < DateTime.UtcNow)
            {
                token.CheckRefreshToken = false;
                return(token);
            }
            check.Delete(false);
            await refreshRepository.SaveChangesAsync();

            token.UserId            = check.UserId;
            token.CheckRefreshToken = true;
            return(token);
        }
Exemplo n.º 3
0
        public async Task <ApiResponseDto <LoginDto> > Login(UserLoginDto userLoginDto)
        {
            ApiResponseDto <LoginDto> response = null;
            var userToLogin = await _userRepo.FindUserByEmail(userLoginDto.Email.ToLower());

            if (userToLogin == null)
            {
                response = new ApiResponseDto <LoginDto>(401, "Invalid User Credentials", "Authentication error", null);
                return(response);
            }


            if (!VerifyPasswordHash(userLoginDto.Password, userToLogin.PasswordHash, userToLogin.PasswordSalt))
            {
                response = new ApiResponseDto <LoginDto>(401, "Invalid User Credentials", "Authentication error", null);
                return(response);
            }

            if (!userToLogin.IsVerified)
            {
                VerifyUser(userToLogin);
            }

            var tokenClaims = new TokenClaimsDto()
            {
                Id    = userToLogin.Id,
                Email = userToLogin.Email,
                Role  = "User"
            };

            var token    = _tokenUtil.GenerateToken(tokenClaims);
            var loginDto = new LoginDto()
            {
                Token  = token,
                UserId = userToLogin.Id,
                Email  = userToLogin.Email,
                Role   = "User"
            };

            response = new ApiResponseDto <LoginDto>(201, "Valid User Credentials", null, loginDto);
            return(response);
        }
Exemplo n.º 4
0
        public string GenerateToken(TokenClaimsDto tokenClaimsDto)
        {
            Claim[] claims = null;

            if (tokenClaimsDto.Role != null)
            {
                claims = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, tokenClaimsDto.Id.ToString()),
                    new Claim(ClaimTypes.Name, tokenClaimsDto.Email),
                    new Claim(ClaimTypes.Role, tokenClaimsDto.Role)
                };
            }
            else
            {
                claims = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, tokenClaimsDto.Id.ToString()),
                    new Claim(ClaimTypes.Name, tokenClaimsDto.Email)
                };
            }


            var key = new SymmetricSecurityKey(Encoding
                                               .UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = credentials
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Exemplo n.º 5
0
        public async Task GenerateRefreshToken_CorrectModel_ReturnAccessRefreshToken()
        {
            TokenClaimsDto token = new TokenClaimsDto()
            {
                UserId = 2
            };

            mockUsersRepository
            .Setup(p => p.FindByIdDetailsAsync(token.UserId))
            .ReturnsAsync(new User()
            {
                Email        = "*****@*****.**",
                HashPassword = "******",
                UserId       = 2,
                RoleOfUser   = RoleOfWorker.Worker
            });
            var tokenGeneratorService = new Mock <TokenGeneratorService>();
            var services = new TokenService(mockRefreshRepository.Object, mockUsersRepository.Object, tokenGeneratorService.Object);
            //Act
            var result = await services.GenerateRefreshTokenAsync(token);

            //Assert
            Assert.Equal(200, result.Code);
        }