public async Task <IActionResult> CheckLogin([FromBody] LoginRequestVM loginrequest) { try { var authenticatedUserDetails = await _context.Login.Include(x => x.Register).Where(x => x.Username == loginrequest.Username && x.Password == loginrequest.Password).ToListAsync(); //await _context.SaveChangesAsync(); if (!authenticatedUserDetails.Any()) { return(NotFound()); } var userDetails = authenticatedUserDetails.FirstOrDefault(); var response = new LoginResponseVM() { UserId = userDetails.Register.Id, Name = userDetails.Register.FirstName }; return(Ok(response)); } catch (Exception) { throw; } }
// https://www.c-sharpcorner.com/article/asp-net-core-web-api-creating-and-validating-jwt-json-web-token/ private string GetAuthToken(LoginResponseVM resp) { //Create a List of Claims, Keep claims name short var permClaims = new List <Claim>(); permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); permClaims.Add(new Claim("UserName", resp.UserAuthInfoVM.UserName)); permClaims.Add(new Claim("UserId", resp.UserAuthInfoVM.UserId)); permClaims.Add(new Claim("FactoryName", resp.FactoryVM.Name)); permClaims.Add(new Claim("FactoryId", resp.FactoryVM.Id)); var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345")); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var tokeOptions = new JwtSecurityToken( issuer: "http://localhost:63048", audience: "http://localhost:4200", claims: permClaims, expires: DateTime.Now.AddHours(8), signingCredentials: signinCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); return(tokenString); // return Ok(new { Token = tokenString }); }
public IHttpActionResult Authenticate([FromBody] LoginVM loginVM) { var loginResponse = new LoginResponseVM(); var loginrequest = new LoginVM { Email = loginVM.Email.ToLower(), Password = loginVM.Password }; string result = checkCredentials(loginrequest.Email, loginrequest.Password); // if credentials are valid if (result == "Admin") { var token = CreateToken(loginrequest.Email, result); //return the token return(Ok(new { Token = token, Role = result, Name = "deepak" })); } else if (result == "User") { var token = CreateToken(loginrequest.Email, result); //return the token return(Ok(new { Token = token, Role = result, Name = "pushpendra" })); } else { loginResponse.StatusCode = HttpStatusCode.Unauthorized.ToString(); return(Unauthorized()); } }
public ActionResult <LoginResponseVM> Login([FromBody] LoginVM user) { if (user == null) { return(BadRequest("Invalid client request")); } LoginResponseVM resp = _serviceWrapper.UserAuthInfoService.IsUserAuthentic(user); return(resp); }
public async Task <ActionResult> Login(UsuarioLoginVM usuarioLoginVM) { if (!ModelState.IsValid) { return(CustomResponse(ModelState)); } var result = await _signInmanager.PasswordSignInAsync(usuarioLoginVM.Email, usuarioLoginVM.Senha, false, true); if (result.Succeeded) { var usuario = await _usermanager.FindByEmailAsync(usuarioLoginVM.Email); var roles = await _usermanager.GetRolesAsync(usuario); var identityClaims = new ClaimsIdentity(); identityClaims.AddClaims(await _usermanager.GetClaimsAsync(usuario)); var token = TokenService.GerarToken(usuario, identityClaims, roles, _tokenConfig); var response = new LoginResponseVM { Token = token, ExpiraEm = 0, Usuario = new TokenUsuarioVM { Id = usuario.Id, Email = usuario.Email, Claims = identityClaims.Claims.Select(c => new ClaimVM { Tipo = c.Type, Valor = c.Value }) } }; _logger.LogInformation($"Novo login usuário: {usuario.Email}"); return(CustomResponse(response)); } if (result.IsLockedOut) { NotificarErro("Usuário temporariamente bloqueado."); return(CustomResponse()); } NotificarErro("Usuário inválido"); return(CustomResponse()); }
public LoginResponseVM IsUserAuthentic(LoginVM loginVM) { LoginResponseVM response = new LoginResponseVM(); List <UserAuthInfo> user = _repositoryWrapper .UserAuthInfo .FindByCondition(x => x.UserName == loginVM.UserName && x.Password == loginVM.Password) .Include(x => x.Factory) .ToList(); if (user == null) { response.ResponseMessage = "No User Exist"; } else if (user.Count() == 1) { List <UserRole> roleList = _repositoryWrapper .UserRole .FindByCondition(x => x.UserId == user.FirstOrDefault().Id) .Include(x => x.Role) .Include(x => x.UserAuthInfo) .ToList(); response.UserAuthInfoVM = _utilService.Mapper.Map <UserAuthInfo, UserAuthInfoVM>(user.FirstOrDefault()); response.FactoryVM = _utilService.Mapper.Map <Factory, FactoryVM>(user.FirstOrDefault().Factory); response.RoleVM = _utilService.Mapper.Map <Role, RoleVM>(roleList.FirstOrDefault().Role); response.LoginSuccess = true; response.Leader = false; if (response.RoleVM.Name == "SUPER_ADMIN") { response.Leader = true; } response.ResponseMessage = "Login Success"; response.AuthToken = GetAuthToken(response); } else if (user.Count() > 1) { response.ResponseMessage = "Multiple User Exist With Same Username"; } return(response); }
public IHttpActionResult Authenticate([FromBody] LoginVM loginVM) { var loginResponse = new LoginResponseVM(); var loginrequest = new LoginVM { Email = loginVM.Email.ToLower(), Password = loginVM.Password }; var isUsernamePasswordValid = loginrequest.Password == "admin"; // if credentials are valid if (isUsernamePasswordValid) { var token = CreateToken(loginrequest.Email); //return the token return(Ok(token)); } // if credentials are not valid send unauthorized status code in response loginResponse.responseMsg.StatusCode = HttpStatusCode.Unauthorized; IHttpActionResult response = ResponseMessage(loginResponse.responseMsg); return(response); }
public IHttpActionResult Authenticate([FromBody] JObject credentials) { if (credentials == null) { return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, $"Sorry, but your credentials came in unsupported format."))); } Dictionary <string, object> credentialsData = _jsonToDictionaryConverter.ProvideAPIDataFromJSON(credentials); string username = string.Empty; string password = string.Empty; foreach (var s in credentialsData) { if (s.Key.Contains("username")) { username = s.Value.ToString(); } if (s.Key.Contains("password")) { password = s.Value.ToString(); } } var loginResponse = new LoginResponseVM(); bool isUsernamePasswordValid = _userValidator.ValidateUser(username, password, out Utility_class_User validatedUserModel); //if credentials are invalid if (!isUsernamePasswordValid) { FailedAttemptsFacade failedFacade = FlyingCenterSystem.GetInstance().getFacede <FailedAttemptsFacade>(); FailedLoginAttempt attemptByPassword = failedFacade.GetByPassword(password); FailedLoginAttempt attempByUsername = failedFacade.GetByUserName(username); bool attemptsComparsion = Statics.BulletprofComparsion(attemptByPassword, attempByUsername); if (!attemptsComparsion) { return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Your username or password is incorrect, also there is no consistency between them! Acsess denied."))); } long failedAttemptNum = 0; long failedAttemptNumToDisplay = 1; bool isTheAttemptIsFirts = attemptByPassword.Equals(new FailedLoginAttempt()); if (isTheAttemptIsFirts) { failedFacade.AddBlackUser(new FailedLoginAttempt(username, password, 2, DateTime.Now)); } else { //long.TryParse(ConfigurationManager.AppSettings["Permitted_Login_Attempts_Num"], out long permittedLOginAttempts); if (attemptByPassword.FAILED_ATTEMPTS_NUM <= 3) { failedAttemptNum = attemptByPassword.FAILED_ATTEMPTS_NUM; failedAttemptNumToDisplay = failedAttemptNum; failedAttemptNum++; attemptByPassword.FAILED_ATTEMPTS_NUM = failedAttemptNum; bool isUpdated = failedFacade.UpdateBlackUser(attemptByPassword); } else { if (DateTime.Now.AddDays(-1) < attemptByPassword.FAILURE_TIME) { TimeSpan timeRemainder = new TimeSpan(24, 0, 0) - DateTime.Now.Subtract(attemptByPassword.FAILURE_TIME); return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, $"Sorry, but the system didn't regocnyzed you as registered user. Your accsess is denied. You're had tried to aouthorize more tham 3 times. Wait {timeRemainder.Hours} hours and {timeRemainder.Minutes} minutes until new attempt!"))); } else { failedAttemptNum = 1; attemptByPassword.FAILED_ATTEMPTS_NUM = failedAttemptNum; attemptByPassword.FAILURE_TIME = DateTime.Now; bool updated = failedFacade.UpdateBlackUser(attemptByPassword); } } } return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, $"Sorry, but the system didn't regocnyzed you as registered user. Your accsess is denied. You're had tried to aouthorize {failedAttemptNumToDisplay} times."))); } //if credentials are valid if (isUsernamePasswordValid) { var token = _jwtService.CreateToken(validatedUserModel); return(Ok(token)); } //if credentials are nt valid send unathorized status code in response loginResponse.responseMsg.StatusCode = HttpStatusCode.Unauthorized; IHttpActionResult response = ResponseMessage(loginResponse.responseMsg); return(response); }