You are here

public function BasicAuth::challengeException in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php \Drupal\basic_auth\Authentication\Provider\BasicAuth::challengeException()

Constructs an exception which is used to generate the challenge.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The request.

\Exception $previous: The previous exception.

Return value

\Symfony\Component\HttpKernel\Exception\HttpExceptionInterface|null An exception to be used in order to generate an authentication challenge.

Overrides AuthenticationProviderChallengeInterface::challengeException

File

core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php, line 137

Class

BasicAuth
HTTP Basic authentication provider.

Namespace

Drupal\basic_auth\Authentication\Provider

Code

public function challengeException(Request $request, \Exception $previous) {
  $site_config = $this->configFactory
    ->get('system.site');
  $site_name = $site_config
    ->get('name');
  $challenge = new FormattableMarkup('Basic realm="@realm"', [
    '@realm' => !empty($site_name) ? $site_name : 'Access restricted',
  ]);

  // A 403 is converted to a 401 here, but it doesn't matter what the
  // cacheability was of the 403 exception: what matters here is that
  // authentication credentials are missing, i.e. this request was made
  // as an anonymous user.
  // Therefore, the following actions will be taken:
  // 1. Verify whether the current user has the 'anonymous' role or not. This
  //    works fine because:
  //    - Thanks to \Drupal\basic_auth\PageCache\DisallowBasicAuthRequests,
  //      Page Cache never caches a response whose request has Basic Auth
  //      credentials.
  //    - Dynamic Page Cache will cache a different result for when the
  //      request is unauthenticated (this 401) versus authenticated (some
  //      other response)
  // 2. Have the 'config:user.role.anonymous' cache tag, because the only
  //    reason this 401 would no longer be a 401 is if permissions for the
  //    'anonymous' role change, causing the cache tag to be invalidated.
  // @see \Drupal\Core\EventSubscriber\AuthenticationSubscriber::onExceptionSendChallenge()
  // @see \Drupal\Core\EventSubscriber\ClientErrorResponseSubscriber()
  // @see \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onAllResponds()
  $cacheability = CacheableMetadata::createFromObject($site_config)
    ->addCacheTags([
    'config:user.role.anonymous',
  ])
    ->addCacheContexts([
    'user.roles:anonymous',
  ]);
  return $request
    ->isMethodCacheable() ? new CacheableUnauthorizedHttpException($cacheability, (string) $challenge, 'No authentication credentials provided.', $previous) : new UnauthorizedHttpException((string) $challenge, 'No authentication credentials provided.', $previous);
}