///<summary>Implements IAuthenticationnService.LogIn</summary> /// <exception cref="InvalidOperationException"> /// Thrown when login failed. /// </exception> public string LogIn(UserForLogIn userForLogIn) { if (userForLogIn.Equals(null)) { throw new ArgumentNullException(); } using (SqlConnection connection = new SqlConnection(_connectionString)) { connection.Open(); string hashedPassword = connection.QueryFirstOrDefault <string>("Select Password From [User] Where Username = @Username;", new { Username = userForLogIn.Username }); if (hashedPassword == null) { throw new InvalidOperationException("Login failed: No such user."); } if (!BCrypt.Net.BCrypt.Verify(userForLogIn.Password, hashedPassword)) { throw new InvalidOperationException("Login failed: Wrong password."); } var id = connection.QueryFirstOrDefault <Guid>("Select Id From [User] Where Username = @Username;", new { Username = userForLogIn.Username }); return(GenerateToken(userForLogIn, id)); } }
public void LogIn_ValidUser_IsSuccessful() { UserForLogIn userForLogIn = new UserForLogIn(); var authenticationServiceMock = new Mock <IAuthenticationService>(); authenticationServiceMock.Setup(x => x.LogIn(userForLogIn)) .Returns("Some JWT"); var authenticationController = new AuthenticationController(authenticationServiceMock.Object); var result = (OkObjectResult)authenticationController.LogIn(userForLogIn); var json = JsonConvert.SerializeObject(result.Value); var dictionary = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); Assert.IsTrue((bool)dictionary["Success"] == true); }
public void LogIn_UnregisteredUser_ThrowsException() { UserForLogIn userForLogIn = new UserForLogIn(); var authenticationServiceMock = new Mock <IAuthenticationService>(); authenticationServiceMock.Setup(x => x.LogIn(userForLogIn)) .Throws(new InvalidOperationException("Login failed: No such user.")); var authenticationController = new AuthenticationController(authenticationServiceMock.Object); var result = (BadRequestObjectResult)authenticationController.LogIn(userForLogIn); var json = JsonConvert.SerializeObject(result.Value); var dictionary = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); Assert.IsTrue((bool)dictionary["Success"] == false); Assert.AreEqual("Login failed: No such user.", dictionary["Error"]); }
private string GenerateToken(UserForLogIn userForLogIn, Guid id) { var tokenHandler = new JwtSecurityTokenHandler(); var secretKeyBytes = Encoding.ASCII.GetBytes(_secretKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, id.ToString()), new Claim(ClaimTypes.Name, userForLogIn.Username) }), Expires = DateTime.UtcNow.AddMinutes(420), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKeyBytes), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(token)); }
public IActionResult LogIn([FromBody] UserForLogIn userForLogIn) { try { var tokenString = _authenticationService.LogIn(userForLogIn); return(Ok(new { Success = true, Token = tokenString })); } catch (InvalidOperationException invalidOperationException) { return(BadRequest(new { Success = false, Error = invalidOperationException.Message })); } catch (ArgumentNullException argumentNullException) { return(BadRequest(new { Success = false, Error = argumentNullException.Message })); } catch (Exception exception) { return(new ObjectResult(new { Success = false, Error = exception.Message }) { StatusCode = StatusCodes.Status500InternalServerError }); } }