public IActionResult Authenticate([FromBody] UserAuthenticateModel model) { var user = _userService.Authenticate(model); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } // Issue Auth Token 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(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok(new{ Token = tokenString })); }
public async Task <UserDetailsModel> Authenticate(UserAuthenticateModel userAuthModel) { //get user with specified username and password var user = await _context.UsersTbl .Include(udt => udt.UserDetailsTbl) .Where(u => u.Username == userAuthModel.Username && u.Password == userAuthModel.Password && !u.UserDetailsTbl.IsDeleted) .AsNoTracking() .SingleOrDefaultAsync(); // if user not found then show error if (user == null) { throw new BadRequestException(UserValidationMessage.USERNAME_PASSWORD_INCORRECT); } //if admin role is to be verified and user is non-admin then show error if (userAuthModel.CheckAdminRole && user.UserDetailsTbl.RoleId < Role.RoleId.Admin) { throw new BadRequestException(UserValidationMessage.USER_NON_AUTHORIZED_ADMIN_AREA); } // authentication successful return(_mapper.Map <UserDetailsModel>(user.UserDetailsTbl)); // check if password is correct //if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt)) // return null; }
public IActionResult Authenticate([FromBody] UserAuthenticateModel userParam) { var user = _userService.Authenticate(userParam.Username, userParam.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } return(Ok(user.Token)); }
public async Task <ActionResult> Authenticate(UserAuthenticateModel data) { var result = await _authenticationService.Authenticate(data.Username, data.Password); if (result == null) { return(BadRequest(new { message = "Username/password combination was not found." })); } return(Ok(result)); }
public async Task <IActionResult> Authenticate([FromBody] UserAuthenticateModel userModel) { var userDetails = await _userService.Authenticate(userModel); string tokenString = JWTAuthentication.GetToken(userDetails, _appSettings.Secret); // return basic user info (without password) and token to store client side return(Ok(new { userid = userDetails.UserId, token = tokenString })); }
public async Task <IActionResult> Auth([FromBody] UserAuthenticateModel input) { if (input.Email.IndexOf('@') > -1) { //Validate email format string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; Regex re = new Regex(emailRegex); if (!re.IsMatch(input.Email)) { ModelState.AddModelError("Email", "Email is not valid"); } } else { //validate Username format string emailRegex = @"^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$"; Regex re = new Regex(emailRegex); if (!re.IsMatch(input.Email)) { ModelState.AddModelError("Email", "Username is not valid"); } } if (ModelState.IsValid) { if (input.Email.IndexOf('@') > -1) { input.Email = await _userManager.Users.Where(r => r.Email == input.Email) .Select(x => x.UserName).SingleOrDefaultAsync(); } var result = await _signInManager.PasswordSignInAsync(input.Email, input.Password, false, false); if (result.Succeeded) { var appUser = await _userManager.Users.SingleOrDefaultAsync(r => r.UserName == input.Email); var token = await GenerateJwtToken(appUser); return(Ok(token)); } return(Unauthorized()); } return(ValidationProblem()); }
public IActionResult Authenticate([FromBody] UserAuthenticateModel model) { this.logger.LogDebug(string.Format(CultureInfo.InvariantCulture, this.localizer["LogLoginTry"].Value, model?.Username)); var user = this.userService.Authenticate(model); if (user == null) { this.logger.LogWarning(string.Format(CultureInfo.InvariantCulture, this.localizer["LogLoginFailed"].Value, model?.Username)); return(this.BadRequest(new { message = this.localizer["LoginFailed"].Value })); } else { this.logger.LogInformation(string.Format(CultureInfo.InvariantCulture, this.localizer["LogLoginSuccess"].Value, model?.Username)); return(this.Ok(user)); } }
public User Authenticate(UserAuthenticateModel model) { var user = _context.Users.SingleOrDefault(x => x.Username == model.Username); if (user == null) { return(null); } // check if password is correct if (!VerifyPasswordHash(model.Password, user.PasswordHash, user.PasswordSalt)) { return(null); } return(user); }
/// <summary> /// Authentifie un <see cref="User"/>, basé sur le <see cref="UserAuthenticateModel"/> fourni. /// </summary> /// <param name="model">Le <see cref="UserAuthenticateModel"/> à utiliser pour authentifier l'<see cref="Utilisateur"/>.</param> /// <returns>L'<see cref="User">Utilisateur</see> authentifié.</returns> public User Authenticate(UserAuthenticateModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } string hashedPassword = CryptographicHelper.GetHash(model.Password, this.appSettings.Security.HashSalt); User user = this.Entities.Find(x => x.Username == model.Username && x.Password == hashedPassword).FirstOrDefault(); if (user == null) { return(null); } else { if (user.Active == false) { // Account is not active. return(null); } // Generation du token JWT. var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(this.appSettings.Security.JWT.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()), new Claim(ClaimTypes.Email, user.Email.ToString(CultureInfo.InvariantCulture)), }), Expires = DateTime.UtcNow.AddDays(this.appSettings.Security.JWT.DurationInDays), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature), }; SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); user.Token = tokenHandler.WriteToken(token); return(user.WithoutPassword()); } }
public async Task <IActionResult> Authenticate([FromBody] UserAuthenticateModel model) { var user = _userService.Authenticate(model.Username, model.Password); if (user == null) { return(NotFound(user.Username)); } var client = new HttpClient(); var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5001"); if (disco.IsError) { return(Task.FromResult <IActionResult>(BadRequest(disco.Exception.Message)).Result); } // request token var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = "e-commerce", ClientSecret = "secret", Scope = "Catalog-Api" }); return(Ok(new { Id = user.Id, Username = user.Username, FirstName = user.FirstName, LastName = user.LastName, Token = tokenResponse.AccessToken })); }