public void CreateTokenTest()
        {
            //Arrange
            var id = Guid.NewGuid();

            //Act
            var token = _tokenGenerator.CreateToken(id);

            //Assert
            Assert.NotNull(token);
            Assert.Contains(".", token);
        }
예제 #2
0
            public async Task <UserTokenOut> Handle(LoginCommand request, CancellationToken cancellationToken)
            {
                var appUser = await _unitOfWork.Users.GetByEmailAsync(request.Email, cancellationToken);

                if (appUser == null)
                {
                    _appNotificationHandler.AddNotification(Keys.APPUSER, Messages.INVALID_EMAIL_PASSWORD);
                    return(null);
                }

                var passwordResult = _passwordHasher.VerifyHashedPassword(appUser, appUser.Password, request.Password);

                if (passwordResult == PasswordVerificationResult.Failed)
                {
                    _appNotificationHandler.AddNotification(Keys.APPUSER, Messages.INVALID_EMAIL_PASSWORD);
                    return(null);
                }

                var token = await _tokenGenerator.CreateToken(appUser);

                if (string.IsNullOrWhiteSpace(token))
                {
                    _appNotificationHandler.AddNotification(Keys.APPUSER, Messages.TOKEN_NOT_GENERATED);
                    return(null);
                }

                return(new UserTokenOut
                {
                    Name = appUser.Name,
                    Email = appUser.Email,
                    Token = token
                });

                throw new AppException(HttpStatusCode.InternalServerError);
            }
            public async Task <UserDto> Handle(Query request, CancellationToken cancellationToken)
            {
                var user = await userManager.FindByEmailAsync(request.Email);

                if (user == null)
                {
                    throw new RestException(HttpStatusCode.Unauthorized, new { error = "Email or password is invalid." });
                }
                if (!user.EmailConfirmed)
                {
                    throw new RestException(HttpStatusCode.BadRequest, new { email = "Email is not confirmed." });
                }

                var result = await signInManager.CheckPasswordSignInAsync(user, request.Password, false);

                if (result.Succeeded)
                {
                    string role = userManager.GetRolesAsync(user).Result.FirstOrDefault();

                    var jwtToken = tokenGenerator.CreateToken(user);
                    //var refreshToken = await userManager.GenerateUserTokenAsync(user, TokenOptions.DefaultProvider, "RefreshToken");

                    return(new UserDto(user, role, jwtToken));
                }

                throw new RestException(HttpStatusCode.Unauthorized, new { error = "Email or password is invalid." });
            }
예제 #4
0
        public async Task <IActionResult> Login([FromBody] CredentialModel credModel)
        {
            if (credModel == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!_userRepository.UserExists(credModel.UserName))
            {
                _logger.LogError($"{credModel.UserName} does not exist.");
                return(NotFound());
            }

            var user = await _userRepository.GetUser(credModel.UserName);

            if (_hasher.VerifyHashedPassword(user, user.PasswordHash, credModel.Password) == PasswordVerificationResult.Success)
            {
                //Create Token
                var token = await _tokenGenerator.CreateToken(credModel.UserName);

                if (token != null && token.Length > 0)
                {
                    var userModel = _mapper.Map <UserModel>(user);
                    userModel.Token = token;
                    await _signInMgr.SignInAsync(user, false);

                    return(Ok(userModel));
                }
                else
                {
                    _logger.LogError($"Failed to login user {credModel.UserName}.");
                    throw new Exception($"Failed to login user {credModel.UserName}.");
                }
            }
            else
            {
                _logger.LogError($"Failed to login user {credModel.UserName}.");
                throw new Exception($"Failed to login user {credModel.UserName}.");
            }
        }
        public ResponseModelBase <LoginOutput> Post([FromBody] CredentialInput credential)
        {
            var result = _loginAppService.Login(credential);

            if (!result.Error)
            {
                return(_tokenGenerator.CreateToken(result.Payload.FirstOrDefault()));
            }
            return(result);
        }
예제 #6
0
 public UserDto(AppUser user, RoleDto role, ITokenGenerator tokenGenerator, string refreshToken)
 {
     Id           = user.Id;
     FirstName    = user.FirstName;
     LastName     = user.LastName;
     Email        = user.Email;
     Token        = tokenGenerator.CreateToken(user);
     Role         = role;
     RefreshToken = refreshToken;
 }
        // TODO Custom Exceptions
        public async Task <Account> Authenticate(string email, string password)
        {
            var account = await _repository.GetByEmail(email);

            if (account == null)
            {
                throw new AccountByEmailOrPasswordNotFoundException(
                          "A user with this email or password combination does not exist");
            }
            // AppException("There is no user with this email");

            if (!await _hasher.VerifyHash(password, account.Salt, account.Password))
            {
                throw new AccountByEmailOrPasswordNotFoundException(
                          "A user with this email or password combination does not exist");
            }
            // AppException("The password is not correct");

            account.Token = _tokenGenerator.CreateToken(account.Id);

            return(account.RemovePassword().RemoveSalt());
        }
예제 #8
0
        public void Initialize()
        {
            _privateKey = _passwordProvider.GetNextBytePassword(PasswordLength);
            _issuer     = _fixture.Create <string>();
            _audience   = _fixture.Create <string>();

            _tokenDescriptor = new TokenDescriptor
            {
                Issuer         = _issuer,
                Audience       = _audience,
                Ttl            = TtlSeconds,
                ExpirationDate = DateTime.UtcNow.AddSeconds(30),
                PrivateKey     = Convert.ToBase64String(_privateKey),
                IsActive       = true
            };

            _tokenRepository = new Mock <ITokenRepository>();

            _tokenRepository.Setup(x => x.GetAsync(_issuer, _audience, CancellationToken.None))
            .ReturnsAsync(_tokenDescriptor);

            _token = _tokenGenerator.CreateToken(_issuer, _audience, _privateKey, _ttl);
            var stringToken = _handler.WriteToken(_token);

            _tokenModel = new TokenModel(stringToken);

            var configurationOptions = new TokenServiceConfiguration
            {
                ClockSkew = TimeSpan.Zero,
            };

            _tokenServiceConfiguration = new Mock <IOptions <TokenServiceConfiguration> >();
            _tokenServiceConfiguration.Setup(x => x.Value).Returns(configurationOptions);

            _tokenService = new TokenValidationService(_tokenRepository.Object, _tokenGenerator, _tokenServiceConfiguration.Object);
        }