@param Request $request
@return ReceivedAuthnRequest

@SuppressWarnings(PHPMD.NPathComplexity)
5402
public function receiveSignedAuthnRequestFrom(Request $request)
    {
        if (!$this->entityRepository) {
            throw new LogicException(
                'Could not receive AuthnRequest from HTTP Request: a ServiceProviderRepository must be configured'
            );
        }

        if (!$request->isMethod(Request::METHOD_GET)) {
            throw new BadRequestHttpException(sprintf(
                'Could not receive AuthnRequest from HTTP Request: expected a GET method, got %s',
                $request->getMethod()
            ));
        }

        $requestUri = $request->getRequestUri();
        if (strpos($requestUri, '?') === false) {
            throw new BadRequestHttpException(
                'Could not receive AuthnRequest from HTTP Request: expected query parameters, none found'
            );
        }

        list(, $rawQueryString) = explode('?', $requestUri);
        $query = ReceivedAuthnRequestQueryString::parse($rawQueryString);

        if (!$query->isSigned()) {
            throw new UnsignedRequestException('The SAMLRequest is expected to be signed but it was not');
        }

        if (!$this->signatureVerifier->verifySignatureAlgorithmSupported($query)) {
            throw new UnsupportedSignatureException(
                $query->getSignatureAlgorithm()
            );
        }

        $authnRequest = ReceivedAuthnRequest::from($query->getDecodedSamlRequest());

        $currentUri = $this->getFullRequestUri($request);
        if (!$authnRequest->getDestination() === $currentUri) {
            throw new BadRequestHttpException(sprintf(
                'Actual Destination "%s" does not match the AuthnRequest Destination "%s"',
                $currentUri,
                $authnRequest->getDestination()
            ));
        }

        if (!$this->entityRepository->hasServiceProvider($authnRequest->getServiceProvider())) {
            throw new UnknownServiceProviderException($authnRequest->getServiceProvider());
        }

        $serviceProvider = $this->entityRepository->getServiceProvider($authnRequest->getServiceProvider());

        // Note: verifyIsSignedBy throws an Exception when the signature does not match.
        if (!$this->signatureVerifier->verifyIsSignedBy($query, $serviceProvider)) {
            throw new SignatureValidationFailedException(
                'Validation of the signature in the AuthnRequest failed'
            );
        }

        return $authnRequest;
    }
243216
protected function attemptAuthentication(Request $request)
    {
        $samlResponse = $this->receiveSamlResponse();

        $token = new SamlSpResponseToken($samlResponse, $this->providerKey);

        $token = $this->authenticationManager->authenticate($token);

        return $token;
    }
845974
public function supportRequestToken(Request $request)
    {
        $client = $request->getUser() && $request->getPassword();
        $token = 'refresh_token' == $request->get('grant_type') && $request->get('refresh_token');

        return $client && $token;
    }
834570
public function externalAuthAction(Request $request)
    {
        $this->checkParams($request->query);

        foreach($request->query->all() as $k => $v) {
            $request->request->set($k, $v);
        }

        return $this->getOAuthAction($request);
    }
387176
protected function send(Request $request)
    {
        $request = $this->auth->addCredentialsToRequest($request);

        return $request->send()->json();
    }
137012
public function receive(Request $request)
    {
        $receive = new Receiver($request);
        $webhook = new WebhookHandler($receive->getMessages(), $this->config, $this->debug);
        $webhook->handle();
    }
219089
private function authBasic(Request $request) {
		$user = $this->findUser($request->getUser());
		if ($user !== null && $this->verifyUser($user, $request->getPassword())) {
			$session = $this->findSession($user);
			if ($session === null) {
				$session = $this->createSession($user);
			}
			$this->authenticated = true;

			return $session;
		}
		return null;
	}
191309
protected function sendLockoutResponse(Request $request)
    {
        $seconds = $this->limiter()->availableIn(
            $this->throttleKey($request)
        );

        $message = Lang::get('auth.throttle', ['seconds' => $seconds]);

        $errors = [$this->username() => $message];

        if ($request->expectsJson()) {
            return api([], 422, $message);
        }

        return redirect()->back()
            ->withInput($request->only($this->username(), 'remember'))
            ->withErrors($errors);
    }
573742
public function postAction(Request $request)
    {
        try {
            return $this->createJsonResponse($this->get('oauth.server')->grant(
                $this->getRequestData($request, 'snakelize')
            ));
        } catch (InvalidGrantException $e) {
            return new JsonResponse('Unavailable to create access token : bad credentials.', 401);
        } catch (\InvalidArgumentException $e) {
            return new JsonResponse('Invalid or missing fields for grant type.', 400);
        }
    }
802450
protected function getRequestToken(Request $request)
    {
        /** @var TokenExtractorInterface $tokenExtractor */
        foreach ($this->tokenExtractors as $tokenExtractor) {
            if (($token = $tokenExtractor->extract($request))) {
                return $token;
            }
        }
    }
1128450
public function getHttpRedirectBindingResponse(AuthnRequest $request = null)
    {
        if (is_null($request)) {
            $request = $this->buildAuthnRequest();
        }

        $context = new MessageContext();
        $context->setMessage($request);

        $binding = (new BindingFactory())->create(SamlConstants::BINDING_SAML2_HTTP_REDIRECT);

        return new RedirectResponse($binding->send($context)->getTargetUrl());
    }
203369
public function getAuthenticatedUser(Request $request)
    {
        foreach ($this->authentications as $authentication) {
            if (null !== $user = $authentication->getAuthenticatedUser($request)) {
                return $user;
            }
        }

        return null;
    }
420344
public function loginAction(Request $request): Response
    {
        $session = $request->getSession();

        # https://github.com/FriendsOfSymfony/FOSOAuthServerBundle/blob/master/Resources/doc/a_note_about_security.md
        if ($request->attributes->has('_fos_oauth_server_authorize_enabled') && $session->has('_security.target_path')) {
            if (false !== strpos($session->get('_security.target_path'), $this->router->generate('fos_oauth_server_authorize'))) {
                $session->set('_fos_oauth_server.ensure_logout', true);
            }
        }

        $alreadyLoggedInRedirectRoute = $request->attributes->get('_sylius')['logged_in_route'] ?? null;

        if ($alreadyLoggedInRedirectRoute && $this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
            return new RedirectResponse($this->router->generate($alreadyLoggedInRedirectRoute));
        }

        $lastError = $this->authenticationUtils->getLastAuthenticationError();
        $lastUsername = $this->authenticationUtils->getLastUsername();
        $options = $request->attributes->get('_sylius');
        $template = $options['template'] ?? '@chang/security/login.html.twig';
        $formType = $options['form'] ?? SecurityLoginType::class;
        $form = $this->formFactory->createNamed('', $formType);

        return $this->templateEngine->renderResponse($template, [
            'form' => $form->createView(),
            'last_username' => $lastUsername,
            'last_error' => $lastError,
            'login_check_route' => $request->attributes->get('_sylius')['login_check_route'] ?? null,
            'csrf_parameter' => $request->attributes->get('_sylius')['csrf_parameter'] ?? null,
            'csrf_token_id' => $request->attributes->get('_sylius')['csrf_token_id'] ?? null,
        ]);
    }
838001
public function token(Request $request)
    {
        $authHeader = $request->header('Authorization');

        // Get for Auth Basic
        if (strtolower(substr($authHeader, 0, 5)) !== 'basic') {
            throw new UnauthorizedHttpException('Invalid authorization header, should be type basic');
        }

        // Get credentials
        $credentials = base64_decode(trim(substr($authHeader, 5)));

        list($login, $password) = explode(':', $credentials, 2);

        // Do auth
        if (! $token = auth()->attempt(['email' => $login, 'password' => $password])) {
            throw new UnauthorizedHttpException('Unauthorized login');
        }

        return $this->respondWithToken($token);
    }
1279711
public function authorizeAction(Request $request)
    {
        $context = new Context(Context::CONTEXT_OAUTH2_NATIVE);
        $this->dispatch(PhraseaEvents::PRE_AUTHENTICATE, new PreAuthenticate($request, $context));

        //Check for auth params, send error or redirect if not valid
        $params = $this->oAuth2Adapter->getAuthorizationRequestParameters($request);

        $appAuthorized = false;
        $error = $request->get('error', '');

        /** @var ApiApplicationRepository $appRepository */
        $appRepository = $this->app['repo.api-applications'];
        if (null === $client = $appRepository->findByClientId($params['client_id'])) {
            throw new NotFoundHttpException(sprintf('Application with client id %s could not be found', $params['client_id']));
        }

        $this->oAuth2Adapter->setClient($client);

        $actionAccept = $request->get("action_accept");
        $actionLogin = $request->get("action_login");

        $template = "api/auth/end_user_authorization.html.twig";

        $custom_template = sprintf(
            "%s/config/templates/web/api/auth/end_user_authorization/%s.html.twig"
            , $this->app['root.path']
            , $client->getId()
        );

        if (file_exists($custom_template)) {
            $template = sprintf(
                'api/auth/end_user_authorization/%s.html.twig'
                , $client->getId()
            );
        }

        if (!$this->getAuthenticator()->isAuthenticated()) {
            if ($actionLogin !== null) {
                try {
                    /** @var PasswordAuthenticationInterface $authentication */
                    $authentication = $this->app['auth.native'];
                    if (null === $usrId = $authentication->getUsrId($request->get("login"), $request->get("password"), $request)) {
                        $this->getSession()->getFlashBag()
                            ->set('error', $this->app->trans('login::erreur: Erreur d\'authentification'));

                        return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'login'), $params));
                    }
                } catch (RequireCaptchaException $e) {
                    return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'captcha'), $params));
                } catch (AccountLockedException $e) {
                    return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'account-locked'), $params));
                }

                $user = $this->getUserRepository()->find($usrId);
                $this->getAuthenticator()->openAccount($user);
                $event = new PostAuthenticate($request, new Response(), $user, $context);
                $this->dispatch(PhraseaEvents::POST_AUTHENTICATE, $event);
            } else {
                $r = new Response($this->render($template, array('error' => $error, "auth" => $this->oAuth2Adapter)));
                $r->headers->set('Content-Type', 'text/html');

                return $r;
            }
        }

        $account = $this->oAuth2Adapter->updateAccount($this->getAuthenticatedUser());

        //check if current client is already authorized by current user
        $clients = $appRepository->findAuthorizedAppsByUser($this->getAuthenticatedUser());

        foreach ($clients as $authClient) {
            if ($client->getClientId() == $authClient->getClientId()) {
                $appAuthorized = true;
                break;
            }
        }

        $params['account_id'] = $account->getId();

        if (!$appAuthorized && $actionAccept === null) {
            $params = [
                "auth"  => $this->oAuth2Adapter,
                "error" => $error,
            ];

            $r = new Response($this->render($template, $params));
            $r->headers->set('Content-Type', 'text/html');

            return $r;
        } elseif (!$appAuthorized && $actionAccept !== null) {
            $appAuthorized = (Boolean) $actionAccept;
            if ($appAuthorized) {
                $this->getApiAccountManipulator()
                    ->authorizeAccess($account);
            } else {
                $this->getApiAccountManipulator()
                    ->revokeAccess($account);
            }
        }

        //if native app show template
        if ($this->oAuth2Adapter->isNativeApp($params['redirect_uri'])) {
            $params = $this->oAuth2Adapter->finishNativeClientAuthorization($appAuthorized, $params);

            $r = new Response($this->render("api/auth/native_app_access_token.html.twig", $params));
            $r->headers->set('Content-Type', 'text/html');

            return $r;
        }

        $this->oAuth2Adapter->finishClientAuthorization($appAuthorized, $params);

        // As OAuth2 library already outputs response content, we need to send an empty
        // response to avoid breaking silex controller
        return '';
    }
1175086
public function postLogin(Request $request)
    {
        // Validate the Form Data
        $result = $this->validate($request, [
            'email' => 'required',
            'password' => 'required'
        ]);

        // Assemble Login Credentials
        $credentials = [
            'email' => trim($request->get('email')),
            'password' => $request->get('password'),
        ];
        $remember = (bool)$request->get('remember', false);

        // Attempt the Login
        $result = $this->authManager->authenticate($credentials, $remember);

        // Return the appropriate response
        $path = session()->pull('url.intended', route('dashboard'));
        return $result->dispatch($path);
    }
907356
public function requestAction(Request $request)
    {
        $widget = $request->isXmlHttpRequest();

        $form = $this->getPasswordResetTokenFormFactory()->createRequestForm()->handleRequest($request);

        if (!$form->isSubmitted()) {
            return new Response($this->getPasswordResetTokenFormRenderer()->renderRequestForm($widget, $form));
        }

        $successMessage = 'password_reset_token.action.request.success';

        $passwordResetToken = $this->getPasswordResetTokenFormHandler()->handleRequestForm($form, !$widget, $successMessage);

        if (empty($passwordResetToken)) {
            $html = $this->getPasswordResetTokenFormRenderer()->renderRequestForm($widget, $form);

            return $widget
                ? new AjaxResponse($html, false, FlashNotifierInterface::MESSAGE_FORM_ERROR)
                : new Response($html);
        }
        if ($widget) {
            $webmailLink   = null;
            $webmailLinker = $this->getWebmailLinker();

            if (!empty($webmailLinker)) {
                $webmailLink = $webmailLinker->getProviderByEmailAddress($passwordResetToken->getUser()->getEmail());
            }

            return new AjaxResponse(
                $this->renderView('DarvinUserBundle:PasswordResetToken/widget/request:submitted.html.twig', [
                    'password_reset_token' => $passwordResetToken,
                    'webmail_link'         => $webmailLink,
                ]),
                true,
                $successMessage
            );
        }

        return $this->redirectToRoute('darvin_user_security_login');
    }