Example #1
0
        public UserDto Login(LoginCredentialsDto loginCredentials)
        {
            var user = _dbContext.Users.FirstOrDefault(u => u.UserName == loginCredentials.UserName &&
                                                       u.Password == loginCredentials.Password);

            return(user == null ? null : Mapper.Map <UserDto>(user));
        }
Example #2
0
        private async Task <bool> TryAuthenticateUser(LoginCredentialsDto credentials)
        {
            using var activity = traceActivityDecorator.StartActivity();

            var cacheKey            = CacheKeys.FailedLoginRequests;
            var cacheKeyName        = cacheKey.Name(credentials.Key);
            var usersAndPasswords   = GetUsersAndPasswords();
            var failedLoginRequests = await cache.TryGetAsync <int>(cacheKeyName);

            if (failedLoginRequests.Success && failedLoginRequests.Value >= MaxLoginTries)
            {
                logger.LogInformation($"User {credentials.Key} has {failedLoginRequests.Value} failed login attempts in the last {cacheKey.TimeToLive.TotalHours} hour(s) and cannot login");
                return(false);
            }

            if (!usersAndPasswords.ContainsKey(credentials.Key) || usersAndPasswords[credentials.Key] != credentials.Secret)
            {
                logger.LogInformation($"The given password for the user {credentials.Key} is wrong");
                await cache.SetAsync(cacheKeyName, failedLoginRequests.Value + 1, cacheKey.TimeToLive);

                return(false);
            }

            await cache.SetAsync(cacheKeyName, 0, cacheKey.TimeToLive);

            return(true);
        }
Example #3
0
        public async Task <ActionResult <AuthenticationResponseDto> > LoginAsync(LoginCredentialsDto dto)
        {
            var user = await userManager.FindByNameAsync(dto.Email);

            if (user == null)
            {
                return(BadRequest());
            }

            if (!await userManager.CheckPasswordAsync(user, dto.Password))
            {
                return(BadRequest());
            }

            var accessToken  = tokenGenerator.GenerateAccessToken(user);
            var refreshToken = tokenGenerator.GenerateRefreshToken();

            accountsDbContext.RefreshTokens.Add(new RefreshToken
            {
                Token     = refreshToken,
                ExpiresAt = DateTime.Now.Add(tokenGenerator.Options.RefreshExpiration),
                AppUserId = user.Id
            });
            await accountsDbContext.SaveChangesAsync();

            var response = new AuthenticationResponseDto
            {
                AccessToken  = accessToken,
                RefreshToken = refreshToken
            };

            return(response);
        }
Example #4
0
        public async Task <LoginResponseDto> LoginAsync([FromBody] LoginCredentialsDto credentials)
        {
            using var activity = traceActivityDecorator.StartActivity();
            activity.AddTag("username", credentials.Key);
            activity.AddTag("session", credentials.Session);
            activity.AddTag("type", credentials.Type);

            logger.LogTrace($"Trying to login user {credentials.Key}");

            var response = await RunAllAuthenticationChecksAsync(credentials);

            var tags = new[] {
                new KeyValuePair <string, object>("username", credentials.Key),
                new KeyValuePair <string, object>("session", credentials.Session),
                new KeyValuePair <string, object>("type", credentials.Type)
            }.Concat(MetricTags.GetDefaultTags()).ToArray();

            LoginAttemptsCounter.Add(1, tags);
            LoginSuccessCounter.Add(response.Success ? 1 : 0, tags);
            LoginFailedCounter.Add(response.Success ? 0 : 1, tags);

            if (response.Success && response.Type == LoginResponseType.AuthenticationToken)
            {
                var message = new {
                    User     = credentials.Key,
                    RemoteId = httpContextAccessor?.HttpContext?.Connection?.RemoteIpAddress?.ToString()
                };
                await messageBus.SendMessageAsync("ntfrex.blog.logins", JsonSerializer.Serialize(message));
            }

            logger.LogInformation($"User {credentials.Key} login was {(!response.Success ? "not" : "")} succesfull");
            return(response);
        }
Example #5
0
        public async Task <ActionResult <bool> > CheckUniqueCredentials(LoginCredentialsDto Credentials)
        {
            var Nickname = Credentials.Nickname;
            var result   = await _service.AreCredentialsUnique(Nickname);

            return(Ok(result));
        }
Example #6
0
        public async Task <IActionResult> CreateToken([FromBody] LoginCredentialsDto model)
        {
            try
            {
                var user = await _usrMgr.FindByNameAsync(model.UserName);

                if (user != null)
                {
                    if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)
                    {
                        var token = _usr.CreateToken(user);

                        if (token != null)
                        {
                            return(Ok(new
                            {
                                access_token = token,
                            }));
                        }
                    }
                    return(BadRequest("Invalid username or password"));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }

            return(BadRequest("Failed to generate token"));
        }
        public async Task Login(LoginCredentialsDto credentials)
        {
            var response = await httpClient.PostJsonAsync <AuthenticationResponseDto>($"{authApiUrl}/login", credentials);

            await tokenStorage.SetTokensAsync(response.AccessToken, response.RefreshToken);

            authState.StateChanged();
        }
        public async Task <ActionResult> LogInAsync([FromBody] LoginCredentialsDto loginCredentials)
        {
            // ответ при неправильных данных
            if (string.IsNullOrWhiteSpace(loginCredentials.Username) || string.IsNullOrWhiteSpace(loginCredentials.Password))
            {
                return(BadRequest());
            }

            // определяем имя пользователя или email пришли
            var isEmail = loginCredentials.Username.Contains('@');

            // ищем пользователя
            var user = isEmail ? await _userManager.FindByEmailAsync(loginCredentials.Username) :
                       await _userManager.FindByNameAsync(loginCredentials.Username);

            // если пользователь не найден
            if (user == null)
            {
                return(BadRequest());
            }

            // проверяем пароль
            var isValidPassword = await _userManager.CheckPasswordAsync(user, loginCredentials.Password);

            if (!isValidPassword)
            {
                return(BadRequest());
            }

            // получаем username
            var username = user.UserName;

            // подготавливаем клеймы токена
            var claims = new[]
            {
                // уникальный ID для токена
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),

                new Claim(ClaimsIdentity.DefaultNameClaimType, username)
            };

            var credentials = new SigningCredentials(
                new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"])),
                SecurityAlgorithms.HmacSha256);

            // создаём токен
            var token = new JwtSecurityToken(
                issuer: _configuration["Jwt:Issuer"],
                audience: _configuration["Jwt:Audience"],
                claims: claims,
                signingCredentials: credentials,
                // !ВАЖНО! срок действия токена
                expires: DateTime.Now.AddDays(1));

            // возвращаем успешный результат с токеном
            return(Ok(new JwtSecurityTokenHandler().WriteToken(token)));
        }
        public IActionResult Login([FromBody] LoginCredentialsDto loginCredentials)
        {
            var user = _authService.Login(loginCredentials);

            if (user == null)
            {
                return(BadRequest("Błędny login lub hasło"));
            }
            return(Ok(user));
        }
        public HttpResponseMessage LoginUser(LoginCredentialsDto ObjLoginCredentialsDto)
        {
            var myContent   = JsonConvert.SerializeObject(ObjLoginCredentialsDto);
            var buffer      = System.Text.Encoding.UTF8.GetBytes(myContent);
            var byteContent = new ByteArrayContent(buffer);

            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var result = client.PostAsync("users/login", byteContent).Result;

            return(result);
        }
        private async Task <User> ValidateUser(LoginCredentialsDto credentials)
        {
            var identityUser = await GetUser(credentials.Username);

            if (identityUser != null)
            {
                var result = _userManager.PasswordHasher.VerifyHashedPassword(identityUser, identityUser.PasswordHash, credentials.Password);
                return(result == PasswordVerificationResult.Failed ? null : identityUser);
            }

            return(null);
        }
Example #12
0
        public async Task <AuthResultDto> Authenticate(LoginCredentialsDto loginCredentials)
        {
            var result = new AuthResultDto();

            try
            {
                //Modifiy this logic accordingly based on the authentication technology used.
                var user = await _userManager.FindByNameAsync(loginCredentials.UserName);

                if (user != null && !user.IsDeleted)
                {
                    if (!user.IsEmailConfirmed)
                    {
                        result.IsSucceeded = false;
                        result.ErrorCode   = "ERROR_USER_NOT_ACTIVATED";
                    }
                    else
                    {
                        var response = await _signInManager.PasswordSignInAsync(loginCredentials.UserName, loginCredentials.Password, loginCredentials.IsRememberMe,
                                                                                lockoutOnFailure : false);

                        if (response.Succeeded)
                        {
                            var permissions = (List <string>)_httpContextAccessor.HttpContext.Items["permissions"];
                            var userDto     = GetUserDto(user);
                            return(new AuthResultDto {
                                IsSucceeded = true, Permissions = permissions, User = userDto
                            });
                        }
                        else if (response.RequiresTwoFactor)
                        {
                            return(new AuthResultDto {
                                IsSucceeded = true
                            });
                        }
                    }
                }
                else
                {
                    result.IsSucceeded = false;
                    result.ErrorCode   = "ERROR_INVALID_LOGIN_CREDENTIALS";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                result.IsSucceeded = true;
                result.ErrorCode   = e.Message;
            }
            return(result);
        }
        public virtual async Task <ActionResult <LoginResultDto> > Login(LoginCredentialsDto credentials)
        {
            User user;

            if (credentials == null ||
                (user = await ValidateUser(credentials)) == null)
            {
                throw new UnauthorizedAccessException("Login failed");
            }

            var token = GenerateToken(user, user.UserRoles.Where(r => r.Role.ApplicationId == credentials.ApplicationId).Select(ur => ur.Role.Name).ToList());

            return(Ok(new { Token = token, Username = user.UserName }));
        }
Example #14
0
        public async Task <IActionResult> Login([FromBody] LoginCredentialsDto credentials)
        {
            var userToVerify = await _userManager.FindByNameAsync(credentials.Username);

            var user = await _userManager.CheckPasswordAsync(userToVerify, credentials.Password);

            if (user == false)
            {
                return(StatusCode(401, "Gebruikersnaam of wachtwoord incorrect"));
            }

            string accessToken = GenerateJwtToken(userToVerify);

            return(Ok(new { token = accessToken }));
        }
Example #15
0
        public async Task <ActionResult <UserCompleteDto> > LoginUser([FromBody] LoginCredentialsDto dataDto)
        {
            var data = _mapper.MapFromDto <LoginCredentialsDto, User>(dataDto);

            var result = await _service.LoginUserAsync(data);

            if (result == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            return(new ObjectResult(new
            {
                Login = _mapper.MapToDto <User, LoginCredentialsDto>(result)
            }));
        }
Example #16
0
        public async Task <IActionResult> RefreshAsync(LoginCredentialsDto dto)
        {
            var user = new AppUser
            {
                Email    = dto.Email,
                UserName = dto.Email
            };
            var result = await userManager.CreateAsync(user, dto.Password);

            if (!result.Succeeded)
            {
                return(BadRequest());
            }

            return(Ok());
        }
Example #17
0
        public HttpResponseMessage LoginUser(LoginCredentialsDto ObjLoginCredentialsDto)
        {
            var myContent   = JsonConvert.SerializeObject(ObjLoginCredentialsDto);
            var buffer      = System.Text.Encoding.UTF8.GetBytes(myContent);
            var byteContent = new ByteArrayContent(buffer);

            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var result = client.PostAsync("users/login", byteContent).Result;

            //todo: recuperare l'headers del token e del role
            //string jwt= result.Headers.GetValues("jwt").ToList<string>().FirstOrDefault();
            //string role = result.Headers.GetValues("role").ToList<string>().FirstOrDefault();
            //System.Web.HttpContext.Current.Session["jwt"]= jwt;
            //result.Headers.GetValues("role");
            return(result);
        }
Example #18
0
        public IActionResult Login(LoginCredentialsDto credentials)
        {
            if (credentials.Username is null || credentials.Password is null)
            {
                return(BadRequest(new ApiError("Required username and password")));
            }

            SafeUser?user = _userService.Login(new LoginCredentials(credentials.Username, credentials.Password));

            if (user is null)
            {
                return(BadRequest(new ApiError("Username or password is incorrect")));
            }

            string token = _jwtService.GenerateToken(user.Id);

            return(Ok(new AuthenticatedUserDto(user.Role, token, user.Name, user.Surname)));
        }
        public async Task <ActionResult <LoginUserDetailsDto> > LoginCheck([FromBody] LoginCredentialsDto loginCredentials)
        {
            var result = await _loginService.CheckIfUserExists(loginCredentials.companyEmail);

            if (result == null)
            {
                return(BadRequest("Given email address doesn't exists."));
            }

            var validateCredentials = await _loginService.ValidateCredentials(result, loginCredentials);

            if (validateCredentials == null)
            {
                return(BadRequest("Incorrect Password."));
            }

            return(Ok(validateCredentials));
        }
Example #20
0
        public async Task <IActionResult> Login([FromBody] LoginCredentialsDto credentials)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var user = await _usr.Login(credentials.UserName, credentials.Password);

                return(Ok(_mapper.Map <UserDto>(user)));
            }
            catch (InvalidOperationException ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #21
0
        public async Task <LoginUserDetailsDto> ValidateCredentials(Login result, LoginCredentialsDto credentials)
        {
            LoginUserDetailsDto loginDetails = new LoginUserDetailsDto();

            var hashedPassword = SHA256Hash(credentials.password);

            if (hashedPassword == result.Password)
            {
                var employee = await _employeeRepository.GetEmployeeByIdAsync(result.EmployeeId);

                loginDetails.Name     = employee.FirstName + " " + employee.LastName;
                loginDetails.jwtToken = await GenerateJwtToken(credentials.companyEmail);

                loginDetails.CompanyEmail = credentials.companyEmail;
                loginDetails.employeeId   = result.EmployeeId;

                return(loginDetails);
            }

            return(null);
        }
        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            LblLoginError.Visible = false;
            LoginPageManager    ObjLoginPageManager    = new LoginPageManager();
            LoginCredentialsDto ObjLoginCredentialsDto = new LoginCredentialsDto();

            ObjLoginCredentialsDto.email    = TxtUsername.Text;
            ObjLoginCredentialsDto.password = TxtPassword.Text;
            var result = ObjLoginPageManager.LoginUser(ObjLoginCredentialsDto);


            string RisultatoBoby = result.Content.ReadAsStringAsync().Result;

            if (result.IsSuccessStatusCode)
            {
                Utente ObjUtente = JsonConvert.DeserializeObject <Utente>(RisultatoBoby);
                Response.Cookies["IdUser"].Value = ObjUtente.id.ToString();

                FormsAuthentication.RedirectFromLoginPage
                    (ObjUtente.email, false);
            }
            else
            {
                ErroreDTO ObjErroreDTO = JsonConvert.DeserializeObject <ErroreDTO>(RisultatoBoby);
                LblLoginError.Text    = ObjErroreDTO.errorMessage;
                LblLoginError.Visible = true;
            }
            //bool IsValidUser = ObjLoginManager.ValidateUser(TxtUsername.Text, TxtPassword.Text);
            //bool IsValidUser = true;
            //if (IsValidUser)
            //{
            //    FormsAuthentication.RedirectFromLoginPage
            //                       (TxtUsername.Text, false);
            //}
            //else
            //{
            //    LblLoginError.Visible = true;
            //}
        }
        public async Task <AuthResultDto> Post([FromBody] LoginCredentialsDto loginCredentials)
        {
            var result = await _identityService.Authenticate(loginCredentials);

            return(result);
        }
Example #24
0
        private async Task <LoginResponseDto> RunAllAuthenticationChecksAsync(LoginCredentialsDto credentials)
        {
            if (!await recaptchaManager.ValidateReCaptchaResponseAsync(credentials.CaptchaResponse))
            {
                return(LoginResponseDto.Failed());
            }

            if (!BlogConfiguration.EnableLogins)
            {
                logger.LogDebug($"Logins are disabled");
                return(LoginResponseDto.Failed());
            }

            if (credentials.Type == LoginCredentialsType.UsernamePassword)
            {
                logger.LogDebug($"authenticating by username and password");

                var canAuthenticate = await TryAuthenticateUser(credentials);

                if (!canAuthenticate)
                {
                    return(LoginResponseDto.Failed());
                }

                if (BlogConfiguration.EnableTwoFactorAuth)
                {
                    logger.LogDebug($"generating and sending two factor token");

                    var session = Guid.NewGuid().ToString();
                    await twoFactorAuthenticator.SendAndGenerateTwoFactorTokenAsync(session, credentials.Key);

                    return(new LoginResponseDto
                    {
                        Type = LoginResponseType.TwoFactorToken,
                        Success = true,
                        Value = session
                    });
                }
                else
                {
                    logger.LogDebug($"generating and returning auth token");

                    var token = GenerateAuthenticationToken(credentials.Key);
                    return(new LoginResponseDto
                    {
                        Type = LoginResponseType.AuthenticationToken,
                        Success = true,
                        Value = token
                    });
                }
            }
            else if (credentials.Type == LoginCredentialsType.TwoFactor)
            {
                logger.LogDebug($"authenticating by two factor token");

                if (await twoFactorAuthenticator.TryAuthenticateSecondFactor(credentials.Session, credentials.Key, credentials.Secret))
                {
                    logger.LogDebug($"generating and returning auth token");

                    var token = GenerateAuthenticationToken(credentials.Key);
                    return(new LoginResponseDto
                    {
                        Type = LoginResponseType.AuthenticationToken,
                        Success = true,
                        Value = token
                    });
                }
            }
            return(LoginResponseDto.Failed());
        }
 public Task <AuthResultDto> Authenticate(LoginCredentialsDto loginCredentials)
 {
     throw new NotImplementedException();
 }