Beispiel #1
0
        public async Task <IActionResult> Login(LoginModel model)
        {
            User user = await _usersService.GetUser(model.Login, model.Password);

            if (user is null)
            {
                return(BadRequest("Invalid username or password"));
            }

            await _usersService.Authenticate(user, HttpContext);

            return(RedirectToAction("Me"));
        }
        public async Task <ActionResult <IEnumerable <PointOfInterest> > > GetAll(Guid userId)
        {
            var isAuthenticated = await usersService.Authenticate(new User { Id = userId });

            if (!isAuthenticated)
            {
                return(Forbid());
            }

            var results = await pointsOfInterestService.GetAll();

            results = results.Where(w => w.User != null && w.User.Id == userId);

            return(Ok(results));
        }
Beispiel #3
0
        public IActionResult Authenticate([FromBody] AuthenticateModel authenticateModel)
        {
            AuthenticateUserDto authenticateUserDto =
                _usersService.Authenticate(authenticateModel.Email, authenticateModel.Password);

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

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, authenticateUserDto.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                            SecurityAlgorithms.HmacSha256Signature)
            };
            SecurityToken token       = tokenHandler.CreateToken(tokenDescriptor);
            string        tokenString = tokenHandler.WriteToken(token);

            return(Ok(new
            {
                authenticateUserDto.Id,
                authenticateUserDto.Email,
                authenticateUserDto.FirstName,
                authenticateUserDto.LastName,
                Token = tokenString
            }));
        }
Beispiel #4
0
        public IActionResult Authenticate([FromBody] AuthenticateModel model)
        {
            var user = _usersService.Authenticate(model.LoginId, model.Password);

            //  var cookie = HttpContext.Session;
            if (user == null)
            {
                if (User.Identity.IsAuthenticated)
                {
                    HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                }

                return(BadRequest(new { message = "Username or password is incorrect" }));
            }
            var loginClaims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, user.LoginId.ToString()),
                //new Claim(ClaimTypes.Sid, user.LoginId.ToString())
            };

            var loginIdentity = new ClaimsIdentity(loginClaims, CookieAuthenticationDefaults.AuthenticationScheme);
            var userPrincipal = new ClaimsPrincipal(new[] { loginIdentity });

            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal);



            var result = user;

            return(Ok(result));
        }
Beispiel #5
0
        public IActionResult Authenticate([FromBody] UserDto userDto)
        {
            var user = _userService.Authenticate(userDto.Username, userDto.Password);

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

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(config.GetValue <string>("JWTSecret"));
            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 tokenString = tokenHandler.WriteToken(token);

            HttpContext.Session.SetString("JWToken", tokenString);


            // return basic user info (without password) and token to store client side
            return(Ok(new
            {
                Id = user.Id,
                Username = user.Username,
                Token = tokenString
            }));
        }
Beispiel #6
0
 public UsersMutation(IUsersService usersService)
 {
     Field <UsersType>("AddUser", arguments: new QueryArguments(
                           new QueryArgument <NonNullGraphType <UsersInputType> >()
     {
         Name = "user"
     }
                           ),
                       resolve: context =>
     {
         var receivedUser = context.GetArgument <UserRequest>("user");
         return(usersService.RegisterUser(receivedUser));
     });
     Field <LoginType>("Login", arguments: new QueryArguments(
                           new QueryArgument <NonNullGraphType <LoginInputType> >()
     {
         Name = "login"
     }
                           ),
                       resolve: context =>
     {
         var receivedUser = context.GetArgument <LoginRequest>("login");
         return(usersService.Authenticate(receivedUser.Username, receivedUser.Password));
     });
 }
        public async Task <IActionResult> Authenticate([FromBody] LoginViewModel loginViewModel)
        {
            try
            {
                var user = await _usersService.Authenticate(loginViewModel);

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

                HttpContext.User = await _applicationSignInManager.CreateUserPrincipalAsync(user);

                var tokens = _antiforgery.GetAndStoreTokens(HttpContext);
                Response.Headers.Add("Access-Control-Expose-Headers", "XSRF-REQUEST-TOKEN");
                Response.Headers.Add("XSRF-REQUEST-TOKEN", tokens.RequestToken);

                _logger.LogInformation($"{Environment.NewLine} Authenticate function");
                return(Ok(user));
            }
            catch (Exception ex)
            {
                _logger.LogError($"{Environment.NewLine} {ex.Message}");
                throw;
            }
        }
Beispiel #8
0
        //TODO: Is there any prettier way to do this in .NetCore?
        private User ParseAuthentication(string authorizationHeader)
        {
            var authHeader  = AuthenticationHeaderValue.Parse(authorizationHeader);
            var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter)).Split(':');

            return(userService.Authenticate(credentials[0], credentials[1]));
        }
        public IActionResult Authenticate([FromBody][CustomizeValidator(RuleSet = ("authenticate"))] UsersRequest userRequest)
        {
            var result = _usersService.Authenticate(userRequest.Username, userRequest.Password);

            if (!result.Success)
            {
                return(BadRequest(result.Message));
            }
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, result.Data.UserId.ToString())
                }),
                Expires            = DateTime.UtcNow.AddMinutes(20),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            result.Data.Token = tokenHandler.WriteToken(token);

            return(Ok(result.Data));
        }
        public IActionResult Authenticate([FromBody] LoginModel model)
        {
            var user = _userService.Authenticate(model.Email, model.Password);

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

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = AuthOptions.GetSymmetricSecurityKey();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            // return basic user info and authentication token
            return(Ok(new LoginResponseModel
            {
                Username = user.Email,
                AccessToken = tokenString
            }));
        }
Beispiel #11
0
        public async Task <IActionResult> Login(LoginModel data)
        {
            var user = _userService.Authenticate(data.Loginname, data.Password);

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

            var getToken        = TokenMan.GenToken(user, _jwtsetting, _jwtsetting.Expire);
            var getRefreshToken = TokenMan.GenToken(user, _jwtsetting, _jwtsetting.LongExpire);
            var result          = _usersTokenService.SaveToken(user.Id, getToken.tokenString, getRefreshToken.tokenString,
                                                               getToken.expireTo, getRefreshToken.expireTo);

            if (!result)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            Response.Cookies.Append("jwt_token", JsonConvert.SerializeObject(new
            {
                access_token  = getToken.tokenString,
                refresh_token = getRefreshToken.tokenString
            }),
                                    new CookieOptions()
            {
                Expires  = DateTime.Now.AddMinutes(_jwtsetting.LongExpire),
                HttpOnly = true,
                Path     = "/"
            });
            return(await Task.FromResult(Ok()));
        }
Beispiel #12
0
        public IActionResult Authenticate([FromBody] UsersDto userDto)
        {
            var user = _usersService.Authenticate(userDto.Username, userDto.Password);

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

            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())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            // return basic user info (without password) and token to store client side
            return(Ok(new { Id = user.Id,
                            Username = user.Username,
                            FullName = user.FullName,
                            ImgUrl = user.ImgUrl,
                            Level = user.Level,
                            Points = user.Points,
                            UsersChallenges = user.UsersChallenges,
                            Token = tokenString }));
        }
        public async Task <IActionResult> Login(LoginRequest loginRequest)
        {
            var user = await _usersService.Authenticate(loginRequest.UserName, loginRequest.Password);

            if (user == null)
            {
                return(Unauthorized());
            }
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = AuthenticationHelper.GetSecret(_configuration);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.UserId.ToString()),
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                Audience           = "Audience",
                Issuer             = "Issuer",
                IssuedAt           = DateTime.Now,
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var res   = new LoginResponse
            {
                Token    = tokenHandler.WriteToken(token),
                Scheme   = JwtBearerDefaults.AuthenticationScheme,
                Redirect = _urlHelper.Link("GetUser", new { id = user.UserId })
            };

            return(Ok(res));
        }
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey("Authorization"))
            {
                return(AuthenticateResult.Fail("Missing authorization header"));
            }

            var authHeader      = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
            var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
            var credentials     = Encoding.UTF8.GetString(credentialBytes).Split(":");

            var username = credentials[0];
            var password = credentials[1];


            User user = usersService.Authenticate(username, password);

            if (user == null)
            {
                return(AuthenticateResult.Fail("Invalid username or password"));
            }

            IIdentity       identity  = new ClaimsIdentity(Scheme.Name);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

            // IIdentity identity = new GenericIdentity(user.Login);

            var ticket = new AuthenticationTicket(principal, Scheme.Name);

            return(AuthenticateResult.Success(ticket));
        }
Beispiel #15
0
        public IActionResult Authenticate([FromBody] UserDto userDto)
        {
            var user = _usersService.Authenticate(userDto.Email, userDto.Password);

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

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.Now.AddDays(_appSettings.TokenExpirationDays),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(Ok(new
            {
                user.Id,
                user.Email,
                user.FirstName,
                user.LastName,
                Token = tokenString,
                user.PasswordRecoveryActive,
                user.LocationId,
                user.Group
            }));
        }
Beispiel #16
0
        public IActionResult Authenticate([FromBody]LoginPostModel login)
        {
            var user = _userService.Authenticate(login.Username, login.Password);

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

            return Ok(user);
        }
Beispiel #17
0
        public async Task <IActionResult> Authenticate([FromBody] LoginViewModel loginViewModel)
        {
            var user = await _usersService.Authenticate(loginViewModel);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }
            return(Ok(user));
        }
        public async Task <IActionResult> Authenticate([FromBody] User model)
        {
            var user = await usersService.Authenticate(model.username, model.password);

            if (user == null)
            {
                return(BadRequest(new { message = "username or password is incorrect" }));
            }
            return(Ok(user));
        }
Beispiel #19
0
        public IHttpActionResult GenerateToken([FromBody] User userParam)
        {
            var user = _usersService.Authenticate(userParam.Username, userParam.Password);

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

            return(Ok(user));
        }
        public ActionResult <UserLoginDTO> ValidateUser([FromBody] UserLoginDTO user)
        {
            if (string.IsNullOrEmpty(user.Login) || string.IsNullOrEmpty(user.Password))
            {
                return(null);
            }

            var dto = _userService.Authenticate(user.Login, user.Password);

            return(dto);
        }
Beispiel #21
0
        public async Task <IActionResult> Authenticate(UserLoginRequestViewModel userParam)
        {
            var user = await _usersService.Authenticate(userParam.Email, userParam.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Email or password incorrect" }));
            }

            return(Ok(user));
        }
        public async Task <IActionResult> Authenticate([FromBody] UserLogin user)
        {
            var storedUser = await Service.Authenticate(user);

            if (storedUser == null)
            {
                return(BadRequest("Invalid username or password."));
            }

            return(Ok(storedUser));
        }
Beispiel #23
0
        public async Task <IActionResult> Authenticate([FromBody] LoginUserDto userParam)
        {
            ResponseDto <LoggedInUserDto> userResult = await _usersService.Authenticate(userParam);

            if (userResult.HasErrors)
            {
                return(BadRequest(userResult));
            }

            return(Ok(userResult));
        }
        public IActionResult Authenticate([FromBody] UserDTO userParam)
        {
            var user = _userService.Authenticate(userParam.Username, userParam.Password);

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

            return(Ok(user));
        }
Beispiel #25
0
        [HttpPost("authenticate")]                      //tym postem strzelamy po token
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateCommand command)
        {
            var user = await _usersService.Authenticate(command.Login, command.Password);

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

            return(Ok(user));
        }
Beispiel #26
0
        public IActionResult Authenticate([FromBody] PostLoginDto login)
        {
            var user = _userService.Authenticate(login.Username, login.Password);

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


            return(Ok(user));
        }
Beispiel #27
0
        public void Authenticate_ReturnsUserDto()
        {
            var expected = new User {
                Id = 1
            };

            repositoryMock.Setup(x => x.Authenticate(It.IsAny <string>(), It.IsAny <string>())).Returns(expected);

            var result = service.Authenticate("user", "password");

            Assert.AreEqual(expectedUserDto, result);
        }
        public async Task Login([FromBody] UserAccountDTO user)
        {
            var dto = await _userService.Authenticate(user.Login, user.Password);

            if (dto == null)
            {
                await Response.WriteAsync(JsonConvert.SerializeObject(dto, new JsonSerializerSettings {
                    Formatting = Formatting.Indented
                }));
            }
            await Response.WriteAsync(await _userTokensService.CreateToken(dto));
        }
        public IActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (_usersService.Authenticate(model.Username, model.Password))
                {
                    if (String.IsNullOrEmpty(model.Service))
                    {
                        // The credential authentication was successful, but no service identifier was provided, so the only thing that can be done
                        // is to confirm the authentication
                        model.SuccessMessage = "Authenticated!";
                    }
                    else
                    {
                        if (_ticketService != null)
                        {
                            // The credential authentication was successful, so generate a new service ticket for the authenticated user
                            string newServiceTicket = SERVICE_TICKET_PREFIX + Guid.NewGuid().ToString().ToUpper();
                            // Store the service ticket with the ticket service
                            _ticketService.InsertTicket(newServiceTicket, model.Username);
                            // Build the redirect URL by appending a "ticket" parameter to the service URL provided by the CAS client
                            UriBuilder redirectURL = new UriBuilder(model.Service);
                            var        query       = HttpUtility.ParseQueryString(redirectURL.Query);
                            query["ticket"]   = newServiceTicket;
                            redirectURL.Query = query.ToString();
                            // Redirect the user to the service with the new service ticket
                            return(Redirect(redirectURL.ToString()));
                        }
                        else
                        {
                            // The credential authentication was successful, but no ticket service exists to create and store a service ticket for the
                            // user, which is an unsupported condition
                            throw new InvalidOperationException("User is authenticated, but no ticket service exists to generate a CAS service " +
                                                                "ticket.");
                        }
                    }
                }
                else
                {
                    // The credentials are not valid, so present an error message
                    model.ErrorMessage = "Authentication failed!";
                }
            }
            else
            {
                // The model (form data) is not valid, so present an error message
                model.ErrorMessage = "Model is not valid!";
            }

            return(View(model));
        }
        public IActionResult Authenticate([FromBody] AuthenticationView authenticationView)
        {
            try
            {
                var user = userService.Authenticate(authenticationView.Username, authenticationView.Password);

                // jwt config
                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.UserId.ToString()),
                        new Claim(ClaimTypes.Role, user.Role)
                    }),
                    Expires            = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };

                var token       = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                // return basic user info and token to store client side
                return(Ok(new
                {
                    user.UserId,
                    user.Username,
                    user.RegistrationDate,
                    user.Role,
                    Token = tokenString
                }));
            }
            catch (ArgumentException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (NotFoundInDbException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (Exception ex)
            {
                // Internal Server Error
                return(StatusCode(500, ex.Message));
            }
        }