Starts the authentication scheme.

@param Request                 $request       The request that resulted in an AuthenticationException
@param AuthenticationException $authException The exception that started the authentication process

@return Response
421471
public function start(Request $request, AuthenticationException $authException = null)
    {
        return new JsonResponse(['message' => $authException->getMessage()], Response::HTTP_UNAUTHORIZED);
    }
985790
protected function authenticateRequest(Request $request)
    {
        if ($this->authenticator && $this->authenticate) {
            return $this->authenticator->authenticate($request);
        }

        return $request;
    }
38595
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        $user = $token->getUser();

        $this->dispatcher->dispatch(self::OAUTH_LOGIN_SUCCESS, new UserEvent($user));

        return $this->authResponseService->authenticateResponse($user,
            new Response($this->twig->render('@StarterKitStart/oauth-success.html.twig')));
    }
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 '';
    }
996853
public function authenticate(Request $request, Route $route)
    {
        try {
            if (! $user = JWTAuth::parseToken()->authenticate()) {
                throw new UnauthorizedHttpException('JWTAuth', 'Unable to authenticate with invalid token.');
            }
        } catch (JWTException $exception) {
            throw new UnauthorizedHttpException('JWTAuth', $exception->getMessage(), $exception);
        }

        return $user;
    }
1256779
public function handle($request, Closure $next, ...$scopes)
    {
        $psr = (new DiactorosFactory)->createRequest($request);

        try {
            $psr = $this->server->validateAuthenticatedRequest($psr);
        } catch (OAuthServerException $e) {
            throw new AuthenticationException;
        }

        $this->validateScopes($psr, $scopes);

        return $next($request);
    }
675895
protected function onAuthenticationFailure(AuthenticationRequiredException $exception = null)
    {
        if ($this->view instanceof JsonView) {
            $this->view->assign('value', ['success' => false]);
        } else {
            $this->addFlashMessage('The entered username or password was wrong', 'Wrong credentials', Message::SEVERITY_ERROR, [], ($exception === null ? 1347016771 : $exception->getCode()));
        }
    }
1291791
protected function sessionSection(Request $request): SectionInterface
    {
        if (empty($request->getAttribute(SessionStarter::ATTRIBUTE))) {
            throw new AuthException("Unable to use authorization thought session, no session exists");
        }

        /** @var SessionInterface $session */
        $session = $request->getAttribute(SessionStarter::ATTRIBUTE);

        return $session->getSection($this->section);
    }
118487
public function start(Request $request, AuthenticationException $exception = null)
    {
        if ($exception) {
            $message = $exception->getMessage();
            if (empty($message) && is_callable([$exception, 'getMessageKey'])) {
                $message = $e->getMessageKey();
            }
        } else {
            $message = 'Full authentication is required to access this resource.';
        }

        $content = [
            'errors' => [
                'code' => 401,
                'message' => $this->translator->trans($message, [], 'errors')
            ]
        ];

        return new JsonResponse($content, JsonResponse::HTTP_UNAUTHORIZED);
    }
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);
    }
1030178
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $parser = App::getBean(AuthorizationParserInterface::class);
        if (!$parser instanceof AuthorizationParserInterface) {
            throw new AuthException(ErrorCode::POST_DATA_NOT_PROVIDED, 'AuthorizationParser should implement Swoft\Auth\Mapping\AuthorizationParserInterface');
        }
        $request = $parser->parse($request);
        $response = $handler->handle($request);
        return $response;
    }
408440
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        if ($request->isXmlHttpRequest()) {
            /** @var User $user */
            $user = $token->getUser();
            $roles = $token->getRoles();
            $outputRoles = array();

            foreach ($roles as $role) {
                $outputRoles[] = $this->translator->trans('roles.' . $role->getRole(), array(), 'CodeLoversAngularBundle');
            }

            $output = $this->generator->getUserData($request, $token);

            // notify listeners to allow output modification
            $event = new LoginEvent($user);
            $event->setOutput($output);

            $this->dispatcher->dispatch(AuthEvents::LOGIN_SUCCESS, $event);

            return new JsonResponse($event->getOutput());
        } else {
            if ($targetPath = $request->getSession()->get('_security.target_path')) {
                $url = $targetPath;
            } else {
                $url = $this->getDefaultUrl();
            }

            return new RedirectResponse($url);
        }
    }
886758
public function onAuthenticationFailure( Request $request, AuthenticationException $exception )
	{
		// if AJAX login
		if ( ! $request->isXmlHttpRequest() ) {
			throw new NotFoundHttpException('Must use AJAX Login');
		}

		return new JsonResponse(array(
				"success" => false
		));
	}
144734
public function prepareForAuthentication(Request $request)
    {
        $e = $this->getEvent();
        $e->setRequest($request);

        $e->setName('authenticate.pre');
        $this->getEventManager()->triggerEvent($e);

        $e->setName('authenticate');
        $result = $this->getEventManager()->triggerEventUntil(function ($test) {
            return ($test instanceof Response);
        }, $e);

        if ($result->stopped()) {
            if ($result->last() instanceof Response) {
                return $result->last();
            }

            throw new Exception\AuthenticationEventException(
                sprintf(
                    'Auth event was stopped without a response. Got "%s" instead',
                    is_object($result->last()) ? get_class($result->last()) : gettype($result->last())
                )
            );
        }

        if ($e->getIdentity()) {
            $e->setName('authenticate.success');
            $this->getEventManager()->triggerEvent($e);
            return true;
        }

        $e->setName('authenticate.fail');
        $this->getEventManager()->triggerEvent($e);

        return false;
    }
341817
public function tokenAction(Request $request)
    {
        /** @var PropertyAccess $config */
        $config = $this->app['conf'];

        if ( ! $request->isSecure() && $config->get(['main', 'api_require_ssl'], true) == true) {
            throw new HttpException(400, 'This route requires the use of the https scheme: ' . $config->get(['main', 'api_require_ssl']), null, ['content-type' => 'application/json']);
        }

        $this->oAuth2Adapter->grantAccessToken();
        ob_flush();
        flush();

        // As OAuth2 library already outputs response content, we need to send an empty
        // response to avoid breaking silex controller
        return '';
    }
755408
protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->route('soda.login');
    }
230047
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        $this->dispatcher->dispatch(self::API_GUARD_FAILED, new AuthFailedEvent($request, $exception));

        return $this->removeAuthCookieFromResponse(new Response('Authentication Failed', Response::HTTP_FORBIDDEN));
    }