public async Task <ActionResult <AuthDto> > Register([FromBody] RegisterDto model) { var user = new AppUser { UserName = model.Name, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); AuthDto auth = new AuthDto { Token = GenerateJwtToken(model.Email, user), UserId = user.Id }; return(Ok(auth)); } else { return(BadRequest()); } }
public IActionResult Index(AuthDto dto, string returnUrl = null) { try { if (!ModelState.IsValid) { TempData.Add(TempDataModelStateKey, ModelState); return(RedirectToAction("Index")); } _usersDomain.Authenticate(dto); if (!string.IsNullOrEmpty(returnUrl)) { returnUrl = HttpUtility.UrlDecode(returnUrl); if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } } return(RedirectToAction("Index", "BlogAdmin")); } catch (ShakerDomainException ex) { TempData.Add(TempDataErrorMessageKey, ex.Message); return(RedirectToAction("Index")); } catch (Exception ex) { _logger.LogCritical(ex.Message); TempData.Add(TempDataErrorMessageKey, MessagesGetter.Get(ErrorPresentationMessages.DefaultErrorMessage)); return(RedirectToAction("Index")); } }
public ActionResult Register(UserForRegisterDto userForRegisterDto) { var userExists = _authService.UserExists(userForRegisterDto.Email); if (!userExists.Success) { return(BadRequest(userExists)); } var registerResult = _authService.Register(userForRegisterDto, userForRegisterDto.Password); var tokenResult = _authService.CreateAccessToken(registerResult.Data); if (!tokenResult.Success) { return(BadRequest(tokenResult)); } var loginDto = new UserForLoginDto { Email = userForRegisterDto.Email, Password = userForRegisterDto.Password }; var userToLogin = _authService.Login(loginDto).Data.Id; AuthDto authDto = new AuthDto { UserId = userToLogin, FirstName = registerResult.Data.FirstName, LastName = registerResult.Data.LastName, Token = tokenResult.Data.Token, Expiration = tokenResult.Data.Expiration }; var result = new SuccessDataResult <AuthDto>(authDto, registerResult.Message); return(Ok(result)); }
public async Task <IActionResult> PostUser(/* in case [Apicontroller not using then we need to specify 'FromBody']*/ AuthDto creds) { // first check the state in case we are not using [apicontroller] // if (!ModelState.IsValid) // return BadRequest("Username and password is required field!"); // we do not have explicitly check the validate state as [apicontroller] do things for us. // for the irrespective of the case used by user creds.UserName = creds.UserName.ToLower(); // if user already exist or not if (await _repo.UserExist(creds.UserName)) { return(BadRequest("User already exist with this username")); } // now we create new user var newUser = _mapper.Map <User>(creds); var userCreated = await _repo.Register(newUser, creds.Password); var userToReturn = _mapper.Map <UserDetailDto>(userCreated); // we'll return the created user with route // getuser in string is name of the method of GetUser in usercontroller [http({id}, name="GetUser")] // to pass id we use GetUser method // we have to return detaildto object so we first mapped user to detail and then pass it as 3rd arg return(CreatedAtRoute("GetUser", new { Controller = "User", id = userCreated.Id }, userToReturn)); }
public SMOperationResult <AuthDto, SMResult> Login(LoginDto loginDto) { var userEntity = GetUser(loginDto.Username); if (userEntity == null) { return(null); } var result = SignInManager.CheckPasswordSignInAsync (userEntity, loginDto.Password, false); var roles = (UserManager.GetRolesAsync(userEntity)); var authDto = new AuthDto() { Id = userEntity.Id, Roles = roles.Result .Select(role => (Role)Enum.Parse(typeof(Role), role)) .ToList(), Username = userEntity.UserName }; if (result.Result.Succeeded) { return(new SMOperationResult <AuthDto, SMResult>(authDto, SMResult.Success)); } return(null); }
public async Task <EntityResponse <UserDto> > Login(AuthDto authDto) { try { string query = string.Format("SELECT * FROM Users where Username={0} and Password={1}", authDto.Username, authDto.Password); var data = await DbOperation.RunQueryAsync <UserDto>(query); if (data != null) { return(new EntityResponse <UserDto> { ResponseCode = ResponseCodes.Successful, EntityData = data.FirstOrDefault() }); } return(new EntityResponse <UserDto>() { ResponseCode = ResponseCodes.IncorrectLoginCredentials, ResponseErrorMessage = "HATA" }); } catch (Exception ex) { return(new EntityResponse <UserDto>() { ResponseCode = ResponseCodes.IncorrectLoginCredentials, ResponseErrorMessage = ex.Message }); } }
public BaseResponse <string> Register(AuthDto authDto) { if (FirstOrDefault(u => u.Email.Equals(authDto.Email, StringComparison.InvariantCultureIgnoreCase)) != null) { throw new BadRequestException("Tài khoản đã tồn tại."); } var(salt, hash) = PasswordHelper.GenerateSecurePassword(authDto.Password); var user = new User { Email = authDto.Email, PasswordHash = hash, PasswordSalt = salt, DisplayName = authDto.Email, }; var response = Create(user, out var isSaved); var role = _roleService.FirstOrDefault(r => r.Name.Equals(DefaultRole.User)); if (role == null) { throw new InternalServerErrorException($"Không có role {DefaultRole.User} tồn tại"); } _userRoleService.Create(new UserRole { UserId = response.Id, RoleId = role.Id }, out isSaved); if (!isSaved) { throw new InternalServerErrorException("Không thể đăng ký, vui lòng thử lại"); } return(new BaseResponse <string>(HttpStatusCode.OK, data: "Đăng ký thành công")); }
public async Task <ResultDto <AuthenticatedDto> > LoginAdmin(AuthDto authDto) { var success = await _signInManager.PasswordSignInAsync(authDto.Email, authDto.Senha, false, false); if (!success.Succeeded) { return(ResultDto <AuthenticatedDto> .Validation("Login ou senha inválidos!")); } var applicationUser = await GetUserByEmail(authDto.Email); if (applicationUser.Role != "Administrador") { return(ResultDto <AuthenticatedDto> .Validation("Perfil não é Administrador!")); } var userDto = new UserDto { Id = applicationUser.Id, Nome = applicationUser.Nome, Email = applicationUser.Email, Role = applicationUser.Role, Claims = applicationUser.Claims }; return(ResultDto <AuthenticatedDto> .Success(TokenWrite.WriteToken(userDto, _tokenConfigurations, _signingConfigurations))); }
public async Task <AuthResponseDto> GetToken([FromBody] AuthDto model) { var user = await _userService.AuthValidate(model); if (user == null) { Response.StatusCode = StatusCodes.Status401Unauthorized; return(null); } var now = DateTime.Now; var jwt = new JwtSecurityToken( issuer: AuthConfig.ISSUER, audience: AuthConfig.AUDIENCE, notBefore: now, claims: new List <Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.Username), new Claim(ClaimTypes.Role, user.Role.ToString()) }, expires: now.Add(TimeSpan.FromSeconds(AuthConfig.LIFETIME)), signingCredentials: new SigningCredentials(AuthConfig.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(new AuthResponseDto { Token = encodedJwt }); }
public async Task <IActionResult> Register([FromBody] AuthDto userDto) { if (!ModelState.IsValid) { return(BadRequest("Something went wrong...")); } // set password var password_hash_key = _repo.CreatePasswordWithEncryption(userDto.Password); User user = new User { UserName = userDto.Email, Email = userDto.Email, NormalizedUserName = userDto.Email.ToUpper().Normalize(), NormalizedEmail = userDto.Email.ToUpper().Normalize() }; var isUserEmail = await _user.FindByEmailAsync(user.Email); if (isUserEmail != null) { return(BadRequest("User exist with this email address. kindly provide different email id.")); } var isUserAdded = await _user.CreateAsync(user, userDto.Password); if (!isUserAdded.Succeeded) { return(BadRequest("Something went wrong...")); } var newUser = _mapper.Map <LogInUserDto>(user); return(Created("api/auth/" + user.Id, newUser)); }
public async Task <AuthDto> AuthenticateAsync(AuthLoginDto loginInfo) { var user = await _unitOfWork.UserRepository.FirstOrDefaultAsync(x => x.Username == loginInfo.Username && x.Password == loginInfo.Password); // return null if user not found if (user == null) { return(null); } // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.TokenEncryptionPassword); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var result = new AuthDto(); result.Token = tokenHandler.WriteToken(token); return(result); }
public void Login_Failed_By_Invalid_Password_Test() { Mock <IAuthService> mockService = GetService(); mockService .Setup(service => service.Authenticate(It.IsAny <String>(), It.IsAny <String>())) .Returns((string email, string password) => { var response = new DataDependentResult <User>(); response.Data = null; response.IsValid = false; response.Error = new ErrorDto().Append("Password", "incorrect password"); return(response); }); AuthController controller = new AuthController(mockService.Object); var request = new AuthDto() { Email = "*****@*****.**", Password = "******" }; var actionResult = controller.Login(request) as UnauthorizedObjectResult; Assert.NotNull(actionResult); var errorDto = actionResult.Value as ErrorDto; Assert.NotNull(errorDto); }
public void Login_Success_Test() { Mock <IAuthService> mockService = GetService(); mockService .Setup(service => service.Authenticate(It.IsAny <String>(), It.IsAny <String>())) .Returns((string email, string password) => { var response = new DataDependentResult <User>(); response.Data = new User() { Id = 1 }; response.IsValid = true; response.Error = null; return(response); }); AuthController controller = new AuthController(mockService.Object); var request = new AuthDto() { Email = "*****@*****.**", Password = "******" }; var actionResult = controller.Login(request) as OkObjectResult; Assert.NotNull(actionResult); var tokenDto = actionResult.Value as TokenDto; Assert.NotNull(tokenDto); Assert.IsType <string>(tokenDto.Bearer); }
public async Task <User> SignIn(AuthDto authData) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var json = JsonConvert.SerializeObject(authData); Debug.WriteLine(json); var response = await client.PostAsync(SignInUri, new StringContent(json, Encoding.UTF8, "application/json")); var jsonString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(jsonString); if (string.IsNullOrEmpty(jsonString)) { ServerAuthorizationError = new ErrorsDto <AuthErrorDto> { Message = "Нет ответа от сервера" }; return(null); } if (response.IsSuccessStatusCode) { var jsonData = JsonConvert.DeserializeObject <JsonResponseDto <UserDto> >(jsonString); return(_mapper.Map <User>(jsonData.Data)); } var jsonError = JsonConvert.DeserializeObject <ErrorsDto <AuthErrorDto> >(jsonString); ServerAuthorizationError = jsonError; return(null); } }
public async Task <ActionResult <dynamic> > Authenticate([FromBody] AuthDto model) { try { var user = userRepository.GetUserLogin(model.Login.ToLower()); if (user == null) { return(NotFound(new { message = "User not found with this login" })); } var isEqualPass = BCryptService.PasswordCompare(model.Password, user.Password); if (!isEqualPass) { return(NotFound(new { message = "Password incorrect" })); } var token = TokenService.GenerateToken(user); user.Password = ""; return(new { user = user, token = token }); } catch (Exception ex) { return(CatchError(ex, "Authentication user")); } }
public async Task <ResultDto <AuthenticatedDto> > Login(AuthDto authDto) { var success = await _signInManager.PasswordSignInAsync(authDto.Email, authDto.Senha, false, false); if (!success.Succeeded) { return(ResultDto <AuthenticatedDto> .Validation("Login ou senha inválidos!")); } var applicationUser = await GetUserByEmail(authDto.Email); if (!applicationUser.Estabelecimentos.Any(x => x.EstabelecimentoId == authDto.EstabelecimentoId)) { return(ResultDto <AuthenticatedDto> .Validation("Usuário não vinculado ao estabalecimento!")); } var userDto = new UserDto { Id = applicationUser.Id, Nome = applicationUser.Nome, Email = applicationUser.Email, Role = applicationUser.Role, Claims = applicationUser.Claims, EstabelecimentoId = authDto.EstabelecimentoId, EstabelecimentoNomeUrl = applicationUser.Estabelecimentos.FirstOrDefault(x => x.EstabelecimentoId == authDto.EstabelecimentoId).Url, EstabelecimentoNome = applicationUser.Estabelecimentos.FirstOrDefault(x => x.EstabelecimentoId == authDto.EstabelecimentoId).Nome }; return(ResultDto <AuthenticatedDto> .Success(TokenWrite.WriteToken(userDto, _tokenConfigurations, _signingConfigurations))); }
public async Task <IHttpActionResult> LoginUsernamePassword([FromBody] AuthDto authDto) { if (DtoNotValid(authDto)) { return(BadRequest("One of the parameters was missing")); } try { var token = await _authManager.LoginUser(authDto.Email, authDto.Password); return(Ok(token)); } catch (ArgumentException ex) { return(BadRequest("Incorrect email address and / or password")); } catch (UserBlockedException ex) { return(BadRequest(ex.Message)); } catch (Exception ex) { return(BadRequest("Internal server error")); } }
public IActionResult Auth([FromBody] AuthDto authDto) { var user = this.Context.Users.Where(c => c.Email == authDto.EMail && c.Password == authDto.Password).FirstOrDefault(); if (user == null) { return(NotFound()); } else { var climes = new List <Claim>(); climes.Add(new Claim("UserID", user.Id.ToString())); var tokenDescriptor = new SecurityTokenDescriptor { Expires = DateTime.UtcNow.AddDays(99999), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is my custom Secret key for authnetication")), SecurityAlgorithms.HmacSha256Signature), Subject = new ClaimsIdentity(climes) }; var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(securityToken); return(Ok(new AuthDto() { Id = user.Id, EMail = user.Email, IsAdmin = user.IsAdmin, Name = user.Name, Token = token })); } }
public ActionResult Login(UserForLoginDto userForLoginDto) { var userToLogin = _authService.Login(userForLoginDto); if (!userToLogin.Success) { return(BadRequest(userToLogin)); } var tokenResult = _authService.CreateAccessToken(userToLogin.Data); if (!tokenResult.Success) { return(BadRequest(tokenResult)); } AuthDto authDto = new AuthDto { UserId = userToLogin.Data.Id, FirstName = userToLogin.Data.FirstName, LastName = userToLogin.Data.LastName, Token = tokenResult.Data.Token, Expiration = tokenResult.Data.Expiration, }; var result = new SuccessDataResult <AuthDto>(authDto, userToLogin.Message); return(Ok(result)); }
public async Task <IActionResult> Login([FromBody] AuthDto authUser) { var user = await _usersRep.Authenticate(authUser.Username, authUser.Password); if (user == null) { return(Unauthorized()); } var tokenHandler = new JwtSecurityTokenHandler(); var secretKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_appSettings.Secret)); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(3), SigningCredentials = signinCredentials }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok(new AuthUserDto { Name = user.Name, Token = tokenString })); }
public async Task <ActionResult <UserDto> > Login(AuthDto loginDto) { if (String.IsNullOrEmpty(loginDto.Email)) { return(BadRequest(new APIResponse(400, "email is not allowed to be empty"))); } if (String.IsNullOrEmpty(loginDto.Password)) { return(BadRequest(new APIResponse(400, "password is not allowed to be empty"))); } var user = await _userManager.FindByEmailAsync(loginDto.Email); if (user == null) { return(Unauthorized(new APIResponse(401))); } var result = await _signInManager.CheckPasswordSignInAsync(user, loginDto.Password, false); if (!result.Succeeded) { return(Unauthorized(new APIResponse(401))); } return(new UserDto { Id = user.Id, Token = _tokenService.CreateToken(user), UserName = user.UserName }); }
public IActionResult Authenticate([FromBody] AuthDto authDto) { var author = _authorService.Authenticate(authDto.Username, authDto.Password); if (author == null) { var errorMessage = "Username or password is incorrect."; return(Unauthorized(new ErrorResponseDto { InternalErrorMessage = errorMessage, DisplayErrorMessage = errorMessage })); } else if (!author.IsDeleted.HasValue || author.IsDeleted.Value) { var errorMessage = "This username has been permanently deactiviated."; return(Unauthorized(new ErrorResponseDto { InternalErrorMessage = errorMessage, DisplayErrorMessage = errorMessage })); } else if (!author.IsLocked.HasValue || author.IsLocked.Value) { var errorMessage = "This user has been locked. Please contact system administrator."; return(Unauthorized(new ErrorResponseDto { InternalErrorMessage = errorMessage, DisplayErrorMessage = errorMessage })); } var tokenExpiration = DateTime.Now.AddDays(7); var refreshTokenExpiration = DateTime.Now.AddDays(30); var tokenHandler = new JwtSecurityTokenHandler(); var keyBytes = Encoding.ASCII.GetBytes(_authConfig.Secret); var securityKey = new SymmetricSecurityKey(keyBytes); var tokenDescriptor = new SecurityTokenDescriptor { Issuer = _authConfig.Issuer, Audience = _authConfig.Audience, Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, author.AuthorId.ToString()), new Claim(ClaimTypes.Expiration, tokenExpiration.ToString()) }), Expires = tokenExpiration, SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature), }; var token = tokenHandler.CreateToken(tokenDescriptor); var responseDto = _mapper.Map <AuthResponseDto>(author); responseDto.Token = tokenHandler.WriteToken(token); responseDto.TokenExpirationDate = tokenExpiration; responseDto.RefreshTokenExpirationDate = refreshTokenExpiration; responseDto.RefreshToken = _authorService.EncodeRefreshToken(author.Username, refreshTokenExpiration); return(Ok(responseDto)); }
public UserEntity Login(LoginEntity loginParam) { if (_AuthDal.Login(loginParam.Username, loginParam.Password).Result != null) { auth = _AuthDal.Login(loginParam.Username, loginParam.Password).Result; return(new UserEntity().UserDTOToUser(GetLoggedInUser())); } return(null); }
public BaseResponse <Passport> Login(AuthDto authDto) { var user = FindUser(authDto.UserName); CheckUserPassword(authDto.Password, user); var passport = CreatePassport(user); return(new SuccessResponse <Passport>(passport)); }
public async Task <IActionResult> Login([FromBody] AuthDto logInUserDto) { if (!ModelState.IsValid) { return(BadRequest("Something went wrong...")); } var user = await _user.FindByNameAsync(logInUserDto.Email); if (user == null) { return(BadRequest("No such user exist, please signup!")); } var isPassword = await _user.CheckPasswordAsync(user, logInUserDto.Password); if (isPassword == false) { return(BadRequest("Incorrect UserName or Password.")); } var isLogin = await _signInUser.PasswordSignInAsync(logInUserDto.Email, logInUserDto.Password, false, false); if (isLogin.Succeeded) { var claims = new[] { new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Name, user.UserName) }; var key = new SymmetricSecurityKey( System.Text.Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddMinutes(2000), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var returnUser = _mapper.Map <LogInUserDto>(user); return(Ok(new { token = tokenHandler.WriteToken(token), user = returnUser, message = "Login Successfully" })); } return(BadRequest("Incorrect UserName or Password")); }
private dynamic Authenticate(AuthDto authDto) { if (Authentication.Components.Auth.Authenticate(authDto.User, authDto.Pass).IsValid()) { return(HttpStatusCode.Accepted); } return(HttpStatusCode.Unauthorized); }
public async Task <User> GetUserByCredentials(AuthDto auth) { var user = await _context.Users.FirstOrDefaultAsync(u => u.Email == auth.Email && u.Password == auth.Password ); return(user); }
public async Task <UserDto> Login(AuthDto credentials) { var user = await _usersRepository.GetByUserName(credentials.Username); if (user == null || !await IsPaswordValid(credentials.Password, user.UserPassword)) { return(null); } return(new UserDto(user)); }
private bool DtoNotValid(AuthDto authDto) { if (authDto == null || string.IsNullOrWhiteSpace(authDto.Email) || string.IsNullOrWhiteSpace(authDto.Password)) { return(true); } return(false); }
public ActionResult Post(AuthDto dto) { var user = _auth.Execute(dto); var stringObjekat = JsonConvert.SerializeObject(user); var encrypted = _enc.EncryptString(stringObjekat); return(Ok(new { token = encrypted })); }