public void LoginUser_Should_ReturnUserWithTokenModel() { var userModel = new UserLoginModel { UserName = "******", Password = "******" }; var userDTO = new UserWithTokenDTO { UserName = "******" }; mockService.Setup(s => s.LoginAsync(It.Is <UserLoginDTO>(dto => dto.UserName == userModel.UserName && dto.Password == userModel.Password))).ReturnsAsync(userDTO).Verifiable(); controller.LoginUser(userModel).Result.Result.Should().BeOfType <OkObjectResult>() .Which.Value.Should().BeEquivalentTo(userModel, options => options.ExcludingMissingMembers()); mockService.Verify(); }
public void Authenticate(UserWithTokenDTO user) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()), new Claim(ClaimTypes.Role, user.Role) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); user.Token = tokenHandler.WriteToken(token); }
public async Task <ActionResult <UserWithTokenDTO> > AuthenticateUser(UserAuthenticate userAuthenticate) { var user = await _context.Users.SingleOrDefaultAsync(u => u.Username.Equals(userAuthenticate.Username)); if (user == null) { return(BadRequest(new { message = "Username is incorrect" })); } if (!_userService.VerifyPassword(user, userAuthenticate.Password)) { return(BadRequest(new { message = "Password is incorrect" })); } UserWithTokenDTO userWithToken = _mapper.Map <UserWithTokenDTO>(user); _userService.Authenticate(userWithToken); return(userWithToken); }