Example #1
0
        public AuthenticationResponseDto LoginAuthentication(string UserName, string Password)
        {
            // Get user
            UserDAO userDao = new UserDAO();
            User    user    = userDao.GetFiltered("username", UserName);

            if (user == null)
            {
                user = userDao.GetFiltered("email", UserName);
            }
            if (user == null || !BCrypt.Net.BCrypt.Verify(Password, user.PasswordHash))
            {
                return(new AuthenticationResponseDto()
                {
                    Success = false,
                    ErrorMessage = "Wrong username or password."
                });
            }

            AuthenticationResponseDto dto = new AuthenticationResponseDto();

            dto.Success      = true;
            dto.ErrorMessage = null;
            dto.Claims.Add(new Claim(ClaimTypes.Name, user.UserName));
            dto.Claims.Add(new Claim(ClaimTypes.Email, user.Email));

            // TODO: add role to identity claims
            foreach (Role r in GetUserRoles(user.ID))
            {
                dto.Claims.Add(new Claim(ClaimTypes.Role, r.RoleName));
            }

            return(dto);
        }
Example #2
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);
        }
        public async Task <IActionResult> Authenticate([FromBody] LoginDto loginDto)
        {
            var loginCreds = mapper.Map <LoginCredentials>(loginDto);
            var userId     = await authenticationProcessor.ValidateCredentialsAsync(loginCreds);

            if (userId == 0)
            {
                return(new UnauthorizedResult());
            }

            var response = new AuthenticationResponseDto(userId);

            return(new OkObjectResult(response));
        }
Example #4
0
        private AuthenticationResponseDto GetAuthenticationResponse(CustomUserInformationQueryModel userInformation)
        {
            var authenticationResponseDto = new AuthenticationResponseDto
            {
                UserId      = userInformation.UserId,
                FirstName   = userInformation.FirstName,
                LastName    = userInformation.LastName,
                LoginName   = userInformation.LoginName,
                Email       = userInformation.Email,
                PhoneNumber = userInformation.PhoneNumber,
                RoleId      = userInformation.RoleId,
                FullName    = userInformation.FirstName + ' ' + userInformation.LastName
            };

            return(authenticationResponseDto);
        }
        public IActionResult Authenticate(string UserName, string Password, bool StayLogged)
        {
            UserBLL bll = new UserBLL();
            AuthenticationResponseDto dto = bll.LoginAuthentication(UserName, Password);

            // Check if login successful
            if (!dto.Success)
            {
                return(RedirectToAction("Login"));
            }

            ClaimsIdentity  claimsIdentity = new ClaimsIdentity(dto.Claims, "UserIdentity");
            ClaimsPrincipal principal      = new ClaimsPrincipal(new[] { claimsIdentity });

            HttpContext.SignInAsync(principal);

            return(RedirectToAction("Index", "Home"));
        }
Example #6
0
        public IActionResult Post([FromBody] AuthenticationRequestDto dto)
        {
            var userResult = _userReadConductor.FindAll(e => e.Username == dto.Username && e.Password == dto.Password);

            if (userResult.ResultObject == null)
            {
                return(BadRequest <AuthenticationResponseDto>(null, new Error()
                {
                    Key = "Credentials Incorrect", Message = "Username or Password is incorrect.", ErrorType = ErrorType.Error
                }));
            }

            var user = userResult.ResultObject.FirstOrDefault();

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes("some_big_key_value_here_secret");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, "1")
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            var response = new AuthenticationResponseDto();

            response.Authenticated = true;
            response.FirstName     = user.FirstName;
            response.LastName      = user.LastName;
            response.Username      = user.Username;
            response.Token         = tokenHandler.WriteToken(token);

            return(Ok(response));
        }
        public AuthenticationResponseDto Authenticate(AuthenticationRequestDto authenticationRequestDto)
        {
            AuthenticationResponseDto authenticationResponseDto;

            try
            {
                authenticationResponseDto = reportAuthentication.Authenticate(authenticationRequestDto);
                if (string.IsNullOrEmpty(authenticationResponseDto.LoginName))
                {
                    authenticationResponseDto.ServiceResponseStatus = 0;
                }
                else
                {
                    authenticationResponseDto.ServiceResponseStatus = 1;
                }
            }
            catch (SSException exception)
            {
                authenticationResponseDto = new AuthenticationResponseDto
                {
                    ServiceResponseStatus = 0,
                    ErrorMessage          = exception.Message,
                    ErrorCode             = exception.ExceptionCode
                };
            }
            catch (Exception exception)
            {
                authenticationResponseDto = new AuthenticationResponseDto
                {
                    ServiceResponseStatus = 0,
                    ErrorCode             = ExceptionAttributes.ExceptionCodes.InternalServerError,
                    ErrorMessage          = exception.Message
                };
            }

            return(authenticationResponseDto);
        }
Example #8
0
        public async Task <ActionResult <AuthenticationResponseDto> > RefreshAsync(string oldRefreshToken)
        {
            var token = await accountsDbContext.RefreshTokens.FindAsync(oldRefreshToken);

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

            accountsDbContext.RefreshTokens.Remove(token);

            if (token.ExpiresAt < DateTime.Now)
            {
                return(BadRequest());
            }

            var user = await userManager.FindByIdAsync(token.AppUserId);

            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);
        }