public IActionResult Register([FromBody] RegisterUserModel model) { if (!ModelState.IsValid) { ModelState.AddModelError("error", "invalid request body"); return(BadRequest(ModelState)); } // map model to entity var user = _mapper.Map <User>(model); try { // create user _userService.Create(user, model.Password); AuthenticateUserModel authModel = new AuthenticateUserModel() { Username = user.Username, Password = model.Password }; return(Authenticate(authModel)); } catch (AppException ex) { // return error message if there was an exception return(BadRequest(new { message = ex.Message })); } }
public async Task <IActionResult> Authenticate(AuthenticateUserModel model) { var user = await _userService.Authenticate(model.Username, model.Password); if (user == null) { return(BadRequest(new { message = "Niepoprawna nazwa użytkownika lub hasło" })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_config["Jwt:Key"]); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Name, user.Username), new Claim(ClaimTypes.GivenName, user.FirstName), new Claim(ClaimTypes.Surname, user.LastName), new Claim(ClaimTypes.Role, user.Role), new Claim("password_change_required", user.IsPasswordChangeRequired.ToString()) }), Expires = DateTime.UtcNow.AddHours(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok(new { accessToken = tokenString })); }
public async Task <ApplicationUserDTO> SignUpUserAsync(AuthenticateUserModel newUserToSignUp) { //return something if the user exists - would need changign to pass back an error to suggest user exists, but this means changing object returned var existingUser = await _userManager.FindByEmailAsync(newUserToSignUp.Username); if (existingUser == null) { return(new ApplicationUserDTO()); } var userToCreate = new ApplicationUser { UserName = newUserToSignUp.Username, Email = newUserToSignUp.Username, Hobbies = "Test hobby" }; var resultOfSignUpAttempt = await _userManager.CreateAsync(userToCreate, newUserToSignUp.Password); if (resultOfSignUpAttempt.Succeeded) { await _signInManager.SignInAsync(userToCreate, isPersistent : false); } else { foreach (var error in resultOfSignUpAttempt.Errors) { //log errors } } //return await _userManager.FindByEmailAsync(newUserToSignUp.Username); //var loggedinUser = await _userManager.FindByEmailAsync(newUserToSignUp.Username); return(_mapper.Map <ApplicationUserDTO>(await _userManager.FindByEmailAsync(newUserToSignUp.Username))); //loggedinUser.ProjectTo<ApplicationUserDTO>(_mapper.ConfigurationProvider).ToListAsync(); }
public async Task Should_Login_Work() { AuthenticateUserModel authenticateUserModel = new AuthenticateUserModel() { Email = "*****@*****.**", Password = "******" }; var result = await usersController.Login(Guid.NewGuid(), authenticateUserModel); Assert.That(result, Is.TypeOf <NotFoundObjectResult>()); result = await usersController.Login(Guid.NewGuid(), authenticateUserModel); Assert.That(result, Is.TypeOf <BadRequestObjectResult>()); Assert.That((result as BadRequestObjectResult).Value, Is.EqualTo("Email not confirmed yet")); result = await usersController.Login(Guid.NewGuid(), authenticateUserModel); Assert.That(result, Is.TypeOf <BadRequestObjectResult>()); Assert.That((result as BadRequestObjectResult).Value, Is.EqualTo("Your account belongs to another service. Please contact Health Record Stack Admin")); result = await usersController.Login(new Guid("1183db51-77b8-4b98-84ee-9fd4c6f2adfb"), authenticateUserModel); Assert.That(result, Is.TypeOf <OkObjectResult>()); result = await usersController.Login(new Guid("1183db51-77b8-4b98-84ee-9fd4c6f2adfb"), authenticateUserModel); Assert.That(result, Is.TypeOf <ObjectResult>()); Assert.That((result as ObjectResult).StatusCode, Is.EqualTo(StatusCodes.Status500InternalServerError)); }
public IActionResult Authenticate([FromBody] AuthenticateUserModel model) { var user = _userRepo.Authenticate(model.Username, model.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } 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.UserID.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok(new { UserId = user.UserID, Name = user.Name, Username = user.Username, Email = user.Email, Token = tokenString })); }
public async Task <UserAuthenticatedDto> Authenticate(AuthenticateUserModel authenticateUserModel) { var userFound = await _userRepository.Authenticate(authenticateUserModel); if (userFound == null) { return(null); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(GlobalSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, userFound.Id.ToString()) }), Expires = DateTime.UtcNow.AddMinutes(30), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); userFound.Token = tokenHandler.WriteToken(token); return(userFound); }
public IActionResult Authenticate([FromBody] AuthenticateUserModel authenticationUserModel) { var user = _unitOfWork.Users.Authenticate(authenticationUserModel.Username, authenticationUserModel.Password); if (user == null) { return(BadRequest(new { Message = "Username or password is incorrect." })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddMinutes(_jwtSettings.ExpirationTimeInMinutes), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok(new { Id = user.Id, Username = user.Username, EmailAddress = user.EmailAddress, Token = tokenString })); }
public IActionResult Authenticate([FromBody] AuthenticateUserModel model) { var userToAuthenticate = _userService.Authenticate(model.Email, model.Password); if (userToAuthenticate == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, userToAuthenticate.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic user info and authentication token return(Ok(new { userToAuthenticate.Id, userToAuthenticate.Email, userToAuthenticate.First_Name, userToAuthenticate.Last_Name, userToAuthenticate.Favorites, Token = tokenString })); }
public AuthenticateUserModelTest() { _userModel = new AuthenticateUserModel() { Username = "******", Password = "******" }; }
public IHttpActionResult CreateToken([FromBody] AuthenticateUserModel authenticateUserModel) { var result = _authorizationManager.CreateAuthorizationToken(authenticateUserModel.UserName, authenticateUserModel.Password); if (result.Errors != null && result.Errors.Any()) { return(GetErrorResult(result)); } return(Ok(result.Result)); }
public IHttpActionResult AuthenticateUser([FromBody] AuthenticateUserModel authenticateUserModel) { var authenticationResult = _authorizationManager.AuthenticateUser(authenticateUserModel.UserName, authenticateUserModel.Password); if (authenticationResult.Errors != null && authenticationResult.Errors.Any()) { return(GetErrorResult(authenticationResult)); } return(Ok(authenticationResult.Result)); }
public async Task <UserAuthenticatedDto> Authenticate(AuthenticateUserModel authenticateUserModel) { var user = await _dbContext.Users.SingleOrDefaultAsync(x => x.Username == authenticateUserModel.Username); // check if password is correct if (user == null || !VerifyPasswordHash(authenticateUserModel.Password, user.PasswordHash, user.PasswordSalt)) { return(null); } return(_mapper.Map <UserAuthenticatedDto>(user)); }
public async Task <IActionResult> Login([FromQuery] AuthenticateUserModel model) { var internalUser = await _internalUserService.AuthenticateUser(model.Email, model.Password); var jwt = _jwtHandler.CreateToken(internalUser.Id); return(Ok(new AuthenticationResponseModel { Email = internalUser.Email, Jwt = jwt })); }
public async Task <ActionResult <TokenModel> > LoginAsync([FromBody] AuthenticateUserModel userParam) { TokenModel tokenModel = await _accountService.AuthenticateAsync(userParam.Email, userParam.Password); if (tokenModel != null) { return(Ok(tokenModel)); } else { return(BadRequest(new { message = "Incorrect email or password" })); } }
public IActionResult Authenticate([FromBody] AuthenticateUserModel model) { var User = _DBService.GetUser(model.Email, model.Password); if (User == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } var ReturnUser = _UserService.Authenticate(User); return(Ok(ReturnUser)); }
public async Task <AuthenticationResponseModel> SignInUserAsync(AuthenticateUserModel userToAuthenticate) { var resultOfSignInAttempt = await _signInManager.PasswordSignInAsync(userToAuthenticate.Username, userToAuthenticate.Password, isPersistent : false, lockoutOnFailure : false); if (!resultOfSignInAttempt.Succeeded) { return new AuthenticationResponseModel { ClientModel = new AuthenticationResponseToClientModel { Errors = new[] { "Invalid username or password" } }, RefreshToken = "" } } ; var authenticatedAppUser = await _userManager.FindByEmailAsync(userToAuthenticate.Username); var authenticatedAppUserDTO = _mapper.Map <ApplicationUserDTO>(authenticatedAppUser); JwtSecurityToken jwtSecurityTokenToReturn = GenerateAndReturnJwtSecurityToken(authenticatedAppUserDTO); SecurityToken securityTokenDerrivedFromJwtBuilderCouldReturn = GenerateAndReturnSecurityToken(authenticatedAppUserDTO); var jwtTokenString = new JwtSecurityTokenHandler().WriteToken(jwtSecurityTokenToReturn); var jwtRefreshToken = GenerateAndReturnJwtToken(authenticatedAppUser, jwtSecurityTokenToReturn); await _identityDbContext.JwtRefreshTokens.AddAsync(jwtRefreshToken); await _identityDbContext.SaveChangesAsync(); //below will only work with IDentity tokens, not JWT - so need to create own class for this, and create entity for it //var tester = new RefreshToken(); return(new AuthenticationResponseModel { ClientModel = new AuthenticationResponseToClientModel { User = authenticatedAppUserDTO, JwtAccessToken = jwtTokenString, ExpiresInSeconds = _authSettings.Value.JwtBearer.ExpiryTimeInSeconds, IsAuthenticated = "1", }, RefreshToken = jwtRefreshToken.RefreshTokenId }); }
public async Task <AuthenticatedUserModel> AuthenticateAsync(string username, string password) { var request = new AuthenticateUserModel { Username = username, Password = password }; var response = await client.PostAsJsonAsync("/api/user/authenticate", request); if (!response.IsSuccessStatusCode) { return(null); } return(await response.Content.ReadAsAsync <AuthenticatedUserModel>()); }
public ActionResult SignIn(AuthenticateUserModel userModel) { if (!ModelState.IsValid) { return(View(userModel)); } var resourceURI = @"Authentication/AuthenticateUser"; try { var userData = this.SendPostRequest <AuthenticateUserModel, UserDataModel>(resourceURI, userModel); var dataForAuthenticationDetails = new UserData(); dataForAuthenticationDetails.Roles = userData.Roles; dataForAuthenticationDetails.WebServiceToken = userData.AuthorizationToken; dataForAuthenticationDetails.UserId = userData.UserId; dataForAuthenticationDetails.UserName = userData.UserName; var authTicket = new FormsAuthenticationTicket(2, userModel.UserName, DateTime.Now, DateTime.Now.AddMinutes(5), false, dataForAuthenticationDetails.Serialize() ); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)) { HttpOnly = true }; Response.AppendCookie(authCookie); return(RedirectToAction("MyProfile", "Profile")); } catch (ApiException ex) { return(View(userModel)); } }
public IActionResult Authenticate( [FromBody] AuthenticateRequest model) { var authenticateModel = new AuthenticateUserModel() { Username = model.Username, Password = model.Password, }; AuthenticateUserResult result; Exception ex; if (!_authenticateCommand.TryExecute(authenticateModel, out result, out ex)) { Logger .WithException(ex) .WithField(nameof(model.Username), model.Username) .Error("failed to authenticate"); return(BadRequest(new { message = "Username or password is incorrect" })); } return(Ok(result.AuthenticatedUser)); }
public async Task <ActionResult> Login(Guid tenantid, AuthenticateUserModel authUser) { var user = await _userManager.FindByEmailAsync(authUser.Email); if (user == null) { return(NotFound("User not found")); } if (user != null && !user.EmailConfirmed && await _userManager.CheckPasswordAsync(user, authUser.Password)) { return(BadRequest("Email not confirmed yet")); } var result = await _signInManager.PasswordSignInAsync(authUser.Email, authUser.Password, false, false); if (result.Succeeded) { var userRoles = await _userManager.GetRolesAsync(user); // To-Do: HRS parent site to be allowed for all users. Add HRSUser role to any tenant // && !roles.Contains("HRSUser") if (tenantid != user.TenantId) { return(BadRequest("Your account belongs to another service. Please contact Health Record Stack Admin")); } var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Iss, "Health Record Stack Auth"), new Claim(JwtRegisteredClaimNames.Sub, user.Id), new Claim(JwtRegisteredClaimNames.Aud, user.Id), // new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddMinutes(20)).ToUnixTimeSeconds().ToString()), // new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString(), "DateTime"), new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString(), "DateTime"), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim("Tenant", user.TenantId.ToString()), }; foreach (var userRole in userRoles) { claims.Add(new Claim(ClaimTypes.Role, userRole)); //var role = await _roleManager.FindByNameAsync(userRole); //if (role != null) //{ // var roleClaims = await _roleManager.GetClaimsAsync(role); // foreach (Claim roleClaim in roleClaims) // { // claims.Add(roleClaim); // } //} } var secretBytes = Encoding.UTF8.GetBytes(Options.HealthRecordStackSecret); var key = new SymmetricSecurityKey(secretBytes); var algorithm = SecurityAlgorithms.HmacSha256; var signingCredentials = new SigningCredentials(key, algorithm); var token = new JwtSecurityToken(null, null, claims, DateTime.Now, DateTime.Now.AddMinutes(20), signingCredentials); var tokenJson = new JwtSecurityTokenHandler().WriteToken(token); return(Ok(new TokenModel { Token = tokenJson })); } return(StatusCode(StatusCodes.Status500InternalServerError, "Couldn't login")); }
public async Task <SignedInUser> Authenticate(AuthenticateUserModel authenticateUserModel) { return(await Authenticate(authenticateUserModel.UserName, authenticateUserModel.Password)); }
public async Task <ActionResult <TokenModel> > LoginAsync([FromBody] AuthenticateUserModel userParam) { return(Ok(await _accountService.AuthenticateAsync(userParam.Username, userParam.Password))); }
public async Task <IActionResult> AuthenticateUser(AuthenticateUserModel authenticateUserModel) { var authenticationResult = await this.authenticationService.Authenticate(authenticateUserModel); return(new JsonResult(authenticationResult)); }
public async Task <ActionResult <AuthenticatedUserModel> > Authenticate([FromBody] AuthenticateUserModel model) { return(GetResult(await authenticationService.AuthenticateAsync(model.Username, model.Password))); }
public ActionResult Index(UserDetailsModel model) { UserPrincipal userPrincipal = null; CompanyDTO objSelectedCompany = null; InsiderTradingEncryption.DataSecurity objPwdHash = null; string dominName = string.Empty; string adPath = string.Empty; string strError = string.Empty; string s_debugInfo = string.Empty; Dictionary <string, object> DictDetails = new Dictionary <string, object>(); try { if (!ModelState.IsValid) { string formUsername = model.sUserName; string formPassword = model.sPassword; string sPasswordHash = string.Empty; string javascriptEncryptionKey = Common.ConstEnum.Javascript_Encryption_Key; string userPasswordHashSalt = Common.ConstEnum.User_Password_Encryption_Key; foreach (string key in ConfigurationManager.AppSettings.Keys) { dominName = key.Contains("DirectoryDomain") ? ConfigurationManager.AppSettings[key] : dominName; adPath = key.Contains("DirectoryPath") ? ConfigurationManager.AppSettings[key] : adPath; if (!String.IsNullOrEmpty(dominName) && !String.IsNullOrEmpty(adPath)) { if (compilationSection.Debug) { Common.Common.WriteLogToFile("DominName & adPath read successfully ", null); } using (AuthenticateUserModel AuthenticateUserModel = new AuthenticateUserModel()) { formUsername = DecryptStringAES(formUsername, javascriptEncryptionKey, javascriptEncryptionKey); formPassword = DecryptStringAES(formPassword, javascriptEncryptionKey, javascriptEncryptionKey); objPwdHash = new InsiderTradingEncryption.DataSecurity(); sPasswordHash = objPwdHash.CreateHash(formPassword, userPasswordHashSalt); if (compilationSection.Debug) { Common.Common.WriteLogToFile("Created Hash successfully ", null); } AuthenticateUserModel.AuthenticateUser(dominName, formUsername, formPassword, adPath, out strError, out DictDetails); { if (DictDetails.Count != 0) { return(this.RedirectAndPost(ConfigurationManager.AppSettings["VigilanteURL"].ToString(), DictDetails)); } else { return(View("AuthenticationFailed")); } } } } } if (!string.IsNullOrEmpty(strError)) { //lblError.Text = "Invalid user name or Password!"; if (compilationSection.Debug) { Common.Common.WriteLogToFile("Invalid user name or Password!", null); } return(View("AuthenticationFailed")); } } } catch (Exception ex) { if (compilationSection.Debug) { Common.Common.WriteLogToFile("Exception occured in Index method", ex); } return(View("AuthenticationFailed")); } finally { } return(null); }