UnauthorizedHttpException example

    // 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);
  }

}


namespace Symfony\Component\HttpKernel\Tests\Exception;

use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class UnauthorizedHttpExceptionTest extends HttpExceptionTest
{
    public function testHeadersDefault()
    {
        $exception = new UnauthorizedHttpException('Challenge');
        $this->assertSame(['WWW-Authenticate' => 'Challenge']$exception->getHeaders());
    }

    public function testWithHeaderConstruct()
    {
        $headers = [
            'Cache-Control' => 'public, s-maxage=1200',
        ];

        $exception = new UnauthorizedHttpException('Challenge', '', null, 0, $headers);

        
$this->assertEquals('500', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new \DivisionByZeroError(), 403);
        $this->assertEquals('403', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new \DivisionByZeroError());
        $this->assertEquals('500', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new NotFoundHttpException());
        $this->assertEquals('404', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new UnauthorizedHttpException('Basic realm="My Realm"'));
        $this->assertEquals('401', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new BadRequestHttpException());
        $this->assertEquals('400', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new NotAcceptableHttpException());
        $this->assertEquals('406', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new ConflictHttpException());
        $this->assertEquals('409', $flattened->getStatusCode());

        
Home | Imprint | This part of the site doesn't use cookies.