Convert an authentication exception into an unauthenticated response.

@param  \Illuminate\Http\Request                 $request
@param  \Illuminate\Auth\AuthenticationException $exception
@return \Illuminate\Http\Response
330778
protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        abort(401);

        return redirect()->guest(route(\Platform::port()->slug().'::login'));
    }
884966
public function authenticate()
    {
        $request = ServerRequest::fromGlobals();
        try {
            return $this->resourceServer->validateAuthenticatedRequest($request);
        } catch (OAuthServerException $exception) {
            $message = $exception->getMessage();
            if ($hint = $exception->getHint()) {
                $message .= ' (' . $hint . ')';
            }
            throw Exception::clientException($message, $exception->getHttpStatusCode(), $exception->getErrorType(), $exception->getHttpStatusCode());
        } catch (\Exception $exception) {
            throw Exception::serverException($exception->getMessage(), $exception->getCode());
        }
    }
836009
protected function createUrl(BlockadeException $exception, Request $request)
    {
        //decide where to redirect. login_url for unauthenticated or
        //bad credentials, deny_url for unauthorized or anything else
        if ($exception instanceof AuthenticationException || $exception instanceof CredentialsException) {
            return $this->login_url.'/to'.$request->getPathInfo();
        }

        return $this->deny_url;
    }
238459
private function handleUncaughtException(\Throwable $exception, Request $request) : Response
    {
        $httpException = new HttpInternalServerErrorException('Uncaught exception', $exception);

        return $this->handleHttpException($httpException, $request);
    }
280555
public static function getErrorResponder(Request $request, \Exception $exception)
    {
        if ($request instanceof HttpRequest) {
            return self::getHttpErrorResponder($exception, $request);
        } else {
            $requestType = get_class($request);
            throw new \InvalidArgumentException("Requests of type '{$requestType}' are not supported.");
        }
    }
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));
    }
1183909
public function render($request, Exception $exception)
    {
        $accessarea = str_before(Route::currentRouteName(), '.');

        if ($exception instanceof TokenMismatchException) {
            return intend([
                'back' => true,
                'with' => ['warning' => trans('cortex/foundation::messages.token_mismatch')],
            ]);
        } elseif ($exception instanceof WatsonValidationException) {
            return intend([
                'back' => true,
                'withInput' => $request->all(),
                'withErrors' => $exception->errors(),
            ]);
        } elseif ($exception instanceof ValidationException) {
            return intend([
                'back' => true,
                'withInput' => $request->all(),
                'withErrors' => $exception->errors(),
            ]);
        } elseif ($exception instanceof GenericException) {
            return intend([
                'url' => $exception->getRedirection() ?? route("{$accessarea}.home"),
                'withInput' => $exception->getInputs() ?? $request->all(),
                'with' => ['warning' => $exception->getMessage()],
            ]);
        } elseif ($exception instanceof AuthorizationException) {
            return intend([
                'url' => in_array($accessarea, ['tenantarea', 'managerarea']) ? route('tenantarea.home') : route('frontarea.home'),
                'with' => ['warning' => $exception->getMessage()],
            ]);
        } elseif ($exception instanceof NotFoundHttpException) {
            // Catch localized routes with missing {locale}
            // and redirect them to the correct localized version
            if (config('cortex.foundation.route.locale_redirect')) {
                $originalUrl = $request->url();

                try {
                    $localizedUrl = app('laravellocalization')->getLocalizedURL(null, $originalUrl);

                    // Will return `NotFoundHttpException` exception if no match found!
                    app('router')->getRoutes()->match(request()->create($localizedUrl));

                    return intend([
                        'url' => $originalUrl !== $localizedUrl ? $localizedUrl : route("{$accessarea}.home"),
                        'with' => ['warning' => $exception->getMessage()],
                    ]);
                } catch (Exception $exception) {
                }
            }

            return $this->prepareResponse($request, $exception);
        } elseif ($exception instanceof ModelNotFoundException) {
            $model = $exception->getModel();
            $single = mb_strtolower(mb_substr($model, mb_strrpos($model, '\\') + 1));
            $plural = str_plural($single);

            return intend([
                'url' => $model ? route("{$accessarea}.{$plural}.index") : route("{$accessarea}.home"),
                'with' => ['warning' => trans('cortex/foundation::messages.resource_not_found', ['resource' => $single, 'identifier' => $request->route($single)])],
            ]);
        }

        return parent::render($request, $exception);
    }
1300432
public function render($request, Exception $e)
    {
        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        } elseif ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        } elseif ($e instanceof AuthorizationException) {
            $e = new HttpException(403, $e->getMessage());
        } elseif ($e instanceof ValidationException && $e->getResponse()) {
            return $e->getResponse();
        }

        $fe = FlattenException::create($e);

        $handler = new SymfonyExceptionHandler(\env('APP_DEBUG', false));

        $decorated = $this->decorate($handler->getContent($fe), $handler->getStylesheet($fe));

        $response = new Response($decorated, $fe->getStatusCode(), $fe->getHeaders());

        $response->exception = $e;

        return $response;
    }
562586
public function makeAuthenticationCall()
    {
        $authResponse = $this->call('POST', [
            'grant_type' => 'client_credentials',
            'client_id' => $this->client->getClientID(),
            'client_secret' => $this->client->getClientSecret()
        ], false, ['Content-Type' => 'application/x-www-form-urlencoded'], false, false);

        if (empty($authResponse->getRaw()->access_token)) {
            throw new Exceptions\AuthenticationException;
        }

        return $authResponse;
    }
792349
public function authenticate(RequestInterface $request)
    {
        $token = $this->token();

        if (!$token && !$this->findMatchingArea($request)) {
            return $this;
        }

        if (!$token) {
            throw new AuthenticationException('Unable to authenticate, token is missing');
        }

        foreach ($this->providers as $provider) {
            if (!$provider->supportsToken($token)) {
                continue;
            }

            if (!$provider->authenticate($token)) {
                $this->stash()
                     ->destroy();

                throw new AuthenticationException(sprintf('Token could not be authenticated in provider "%s", destroying token', get_class($provider)));
            }

            $this->user = $provider->get($token);

            return $this;
        }

        $this->stash()
             ->destroy();

        throw new AuthenticationException(sprintf('Missing provider supporting token "%s", destroying token', get_class($token)));
    }
912920
protected function getRequestUser(HTTPRequest $request)
    {
        // Check authentication
        $member = $this->getAuthHandler()->requireAuthentication($request);

        // Check authorisation
        $permissions = $request->param('Permissions');
        if (!$permissions) {
            return $member;
        }

        // If permissions requested require authentication
        if (!$member) {
            throw new Exception("Authentication required");
        }

        // Check authorisation for this member
        $allowed = Permission::checkMember($member, $permissions);
        if (!$allowed) {
            throw new Exception("Not authorised");
        }
        return $member;
    }
1149650
public function getResponse( RequestInterface $request, PhpException $exception ) {
		$response = $this->toResponse( $exception );

		if ( $response !== false ) {
			return $response;
		}

		if ( ! $this->debug ) {
			return Response::error( 500 );
		}

		return $this->toDebugResponse( $request, $exception );
	}
711397
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if ($request->isXmlHttpRequest()) {
            // if AJAX login
            $array = ['message' => $exception->getMessage()];
            $response = new JsonResponse($array, 401);
        } else {
            // if form login
            // set authentication exception to session
            $this->session->set(Security::AUTHENTICATION_ERROR, $exception);
            $response = new RedirectResponse($this->router->generate('sulu_admin.login'));
        }

        return $response;
    }
36542
protected function error(Request $request, \Exception $exception) {
        return $request->getTarget() . ' threw '
        . get_class($exception) . ': '
        . $exception->getMessage() . "\n"
        . $exception->getTraceAsString();
    }
27260
protected function unauthenticated($request, AuthenticationException $e)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        // check if Chronos path
        if ($request->is('admin') || $request->is('admin/*'))
            return redirect()->guest(route('chronos.auth.login'));
        // or app
        else
            return redirect()->guest('login');
    }
1189793
public function handleException(ServerRequestInterface $request, ResponseInterface $response, Exception $exception)
    {
        return $this->withError($response, $exception);
    }
1137019
private function throwExceptionIfRequestRequiresAuthenticationOrReturnResponse(
        string $method,
        Request $request,
        Response $response
    ): Response {
        if ($response->statusCode() === Response::FORBIDDEN) {
            throw new AuthenticationRequiredException(
                sprintf(
                    'Request to "%s %s" requires authentication."',
                    $method,
                    $request->url()
                )
            );
        }

        return $response;
    }