public string Login(LoginModel loginModel) { if (!this._repository.IsExistingUser(loginModel.Email)) { throw new Exception("User is not existing."); } var user = this._repository.GetUserByEmail(loginModel.Email); if (loginModel.Password != PasswordCipher.Decode(user.Password)) { throw new Exception("Incorrect password!"); } var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("UserID", user.UserId.ToString()) }), Expires = DateTime.UtcNow.AddDays(1), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey( Encoding.UTF8 .GetBytes(this._appSettings.JWT_Secret)), SecurityAlgorithms.HmacSha256Signature) }; var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(securityToken); return(token); }
// POST : /api/user/login public IActionResult Login(DomainModels.DomainModels.LoginModel model) { try { var token = this._service.Login(model); return(Ok(new { token })); } catch (Exception ex) { return(StatusCode(406, new AbortedRegistrationError(ex.Message, false))); } }