AccessDeniedHttpException example


  public function setNoJsCookie(Request $request) {
    // This controller may only be accessed when the browser does not support     // JavaScript. It is accessed automatically when that's the case thanks to     // big_pipe_page_attachments(). When this controller is executed, deny     // access when either:     // - the no-JS cookie is already set: this indicates a redirect loop, since     // the cookie was already set, yet the user is executing this controller;     // - there is no session, in which case BigPipe is not enabled anyway, so it     // is pointless to set this cookie.     if ($request->cookies->has(BigPipeStrategy::NOJS_COOKIE) || !$request->hasSession()) {
      throw new AccessDeniedHttpException();
    }

    if (!$request->query->has('destination')) {
      throw new HttpException(400, 'The original location is missing.');
    }

    $response = new LocalRedirectResponse($request->query->get('destination'));
    // Set cookie without httpOnly, so that JavaScript can delete it.     $response->headers->setCookie(new Cookie(BigPipeStrategy::NOJS_COOKIE, TRUE, 0, '/', NULL, FALSE, FALSE, FALSE, NULL));
    $response->addCacheableDependency((new CacheableMetadata())->addCacheContexts(['cookies:' . BigPipeStrategy::NOJS_COOKIE, 'session.exists']));
    return $response;
  }

  public function execute() {
    // Prior to this being called, the $view should already be set to this     // display, and arguments should be set on the view.     $this->view->build();

    if (!empty($this->view->build_info['fail'])) {
      throw new NotFoundHttpException();
    }

    if (!empty($this->view->build_info['denied'])) {
      throw new AccessDeniedHttpException();
    }
  }

  /** * {@inheritdoc} */
  public function optionsSummary(&$categories, &$options) {
    parent::optionsSummary($categories$options);

    $categories['page'] = [
      'title' => $this->t('Page settings'),
      

  public function commentPermalink(Request $request, CommentInterface $comment) {
    if ($entity = $comment->getCommentedEntity()) {
      // Check access permissions for the entity.       if (!$entity->access('view')) {
        throw new AccessDeniedHttpException();
      }
      $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId()$entity->bundle())[$comment->getFieldName()];

      // Find the current display page for this comment.       $page = $this->entityTypeManager()->getStorage('comment')->getDisplayOrdinal($comment$field_definition->getSetting('default_mode')$field_definition->getSetting('per_page'));
      // @todo: Cleaner sub request handling.       $subrequest_url = $entity->toUrl()->setOption('query', ['page' => $page])->toString(TRUE);
      $redirect_request = Request::create($subrequest_url->getGeneratedUrl(), 'GET', $request->query->all()$request->cookies->all()[]$request->server->all());
      // Carry over the session to the subrequest.       if ($request->hasSession()) {
        $redirect_request->setSession($request->getSession());
      }


namespace Symfony\Component\HttpKernel\Tests\Exception;

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

class AccessDeniedHttpExceptionTest extends HttpExceptionTest
{
    protected function createException(string $message = '', \Throwable $previous = null, int $code = 0, array $headers = []): HttpException
    {
        return new AccessDeniedHttpException($message$previous$code$headers);
    }
}

  public function post(EntityInterface $entity = NULL) {
    if ($entity == NULL) {
      throw new BadRequestHttpException('No entity content received.');
    }

    $entity_access = $entity->access('create', NULL, TRUE);
    if (!$entity_access->isAllowed()) {
      throw new AccessDeniedHttpException($entity_access->getReason() ?: $this->generateFallbackAccessDeniedMessage($entity, 'create'));
    }
    $definition = $this->getPluginDefinition();
    // Verify that the deserialized entity is of the type that we expect to     // prevent security issues.     if ($entity->getEntityTypeId() != $definition['entity_type']) {
      throw new BadRequestHttpException('Invalid entity type');
    }
    // POSTed entities must not have an ID set, because we always want to create     // new entities here.     if (!$entity->isNew()) {
      throw new BadRequestHttpException('Only new entities can be created');
    }
public function testNormalize() {
    $request_stack = $this->prophesize(RequestStack::class);
    $request_stack->getCurrentRequest()->willReturn(Request::create('http://localhost/'));
    $container = $this->prophesize(ContainerInterface::class);
    $container->get('request_stack')->willReturn($request_stack->reveal());
    $config = $this->prophesize(ImmutableConfig::class);
    $config->get('error_level')->willReturn(ERROR_REPORTING_DISPLAY_VERBOSE);
    $config_factory = $this->prophesize(ConfigFactory::class);
    $config_factory->get('system.logging')->willReturn($config->reveal());
    $container->get('config.factory')->willReturn($config_factory->reveal());
    \Drupal::setContainer($container->reveal());
    $exception = new AccessDeniedHttpException('lorem', NULL, 13);
    $current_user = $this->prophesize(AccountInterface::class);
    $current_user->hasPermission('access site reports')->willReturn(TRUE);
    $normalizer = new HttpExceptionNormalizer($current_user->reveal());
    $normalized = $normalizer->normalize($exception, 'api_json');
    $normalized = $normalized->getNormalization();
    $error = $normalized[0];
    $this->assertNotEmpty($error['meta']);
    $this->assertNotEmpty($error['source']);
    $this->assertSame('13', $error['code']);
    $this->assertSame('403', $error['status']);
    $this->assertEquals('Forbidden', $error['title']);
    
$tag_list = Tags::explode($input);
      $typed_string = !empty($tag_list) ? mb_strtolower(array_pop($tag_list)) : '';

      // Selection settings are passed in as a hashed key of a serialized array       // stored in the key/value store.       $selection_settings = $this->keyValue->get($selection_settings_key, FALSE);
      if ($selection_settings !== FALSE) {
        $selection_settings_hash = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt());
        if (!hash_equals($selection_settings_hash$selection_settings_key)) {
          // Disallow access when the selection settings hash does not match the           // passed-in key.           throw new AccessDeniedHttpException('Invalid selection settings key.');
        }
      }
      else {
        // Disallow access when the selection settings key is not found in the         // key/value store.         throw new AccessDeniedHttpException();
      }

      $entity_type_id = $request->query->get('entity_type');
      if ($entity_type_id && $this->entityTypeManager()->hasDefinition($entity_type_id)) {
        $entity_id = $request->query->get('entity_id');
        

  protected function validateAndLoadFieldDefinition($entity_type_id$bundle$field_name) {
    $field_definitions = $this->entityFieldManager->getFieldDefinitions($entity_type_id$bundle);
    if (!isset($field_definitions[$field_name])) {
      throw new NotFoundHttpException(sprintf('Field "%s" does not exist', $field_name));
    }

    /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
    $field_definition = $field_definitions[$field_name];
    if ($field_definition->getSetting('target_type') !== 'file') {
      throw new AccessDeniedHttpException(sprintf('"%s" is not a file field', $field_name));
    }

    $entity_access_control_handler = $this->entityTypeManager->getAccessControlHandler($entity_type_id);
    $bundle = $this->entityTypeManager->getDefinition($entity_type_id)->hasKey('bundle') ? $bundle : NULL;
    $access_result = $entity_access_control_handler->createAccess($bundle, NULL, [], TRUE)
      ->andIf($entity_access_control_handler->fieldAccess('edit', $field_definition, NULL, NULL, TRUE));
    if (!$access_result->isAllowed()) {
      throw new AccessDeniedHttpException($access_result->getReason());
    }

    return $field_definition;
  }
/** * Denies access if authentication provider is not allowed on this route. * * @param \Symfony\Component\HttpKernel\Event\RequestEvent $event * The request event. */
  public function onKernelRequestFilterProvider(RequestEvent $event) {
    if (isset($this->filter) && $event->isMainRequest()) {
      $request = $event->getRequest();
      if ($this->authenticationProvider->applies($request) && !$this->filter->appliesToRoutedRequest($request, TRUE)) {
        throw new AccessDeniedHttpException('The used authentication method is not allowed on this route.');
      }
    }
  }

  /** * Respond with a challenge on access denied exceptions if appropriate. * * On a 403 (access denied), if there are no credentials on the request, some * authentication methods (e.g. basic auth) require that a challenge is sent * to the client. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event * The exception event. */

        // Reuse the same DOM id so it matches that in drupalSettings.         $view->dom_id = $dom_id;

        $preview = $view->preview($display_id$args);
        $response->addCommand(new ReplaceCommand(".js-view-dom-id-$dom_id", $preview));
        $response->addCommand(new PrependCommand(".js-view-dom-id-$dom_id", ['#type' => 'status_messages']));

        return $response;
      }
      else {
        throw new AccessDeniedHttpException();
      }
    }
    else {
      throw new NotFoundHttpException();
    }
  }

}
$authentication_manager = $this->getContainer()->get('authentication');
    $account = $authentication_manager->authenticate($request) ?: new AnonymousUserSession();

    /** @var \Drupal\Core\Session\AccountProxyInterface $current_user */
    $current_user = $this->getContainer()->get('current_user');
    $current_user->setAccount($account);

    /** @var \Drupal\system\Access\DbUpdateAccessCheck $db_update_access */
    $db_update_access = $this->getContainer()->get('access_check.db_update');

    if (!Settings::get('update_free_access', FALSE) && !$db_update_access->access($account)->isAllowed()) {
      throw new AccessDeniedHttpException('In order to run update.php you need to either have "Administer software updates" permission or have set $settings[\'update_free_access\'] in your settings.php.');
    }
  }

}

  public function getResetPassForm(Request $request$uid) {
    $session = $request->getSession();
    $timestamp = $session->get('pass_reset_timeout');
    $hash = $session->get('pass_reset_hash');
    // As soon as the session variables are used they are removed to prevent the     // hash and timestamp from being leaked unexpectedly. This could occur if     // the user does not click on the log in button on the form.     $session->remove('pass_reset_timeout');
    $session->remove('pass_reset_hash');
    if (!$hash || !$timestamp) {
      throw new AccessDeniedHttpException();
    }

    /** @var \Drupal\user\UserInterface $user */
    $user = $this->userStorage->load($uid);
    if ($user === NULL || !$user->isActive()) {
      // Blocked or invalid user ID, so deny access. The parameters will be in       // the watchdog's URL for the administrator to check.       throw new AccessDeniedHttpException();
    }

    // Time out, in seconds, until login URL expires.
$replace_token = $request->query->get('replace_token');
    $replace = $request->query->get('replace');
    $lowercase = $request->query->get('lowercase');

    $transliterated = $this->transliteration->transliterate($text$langcode, '_');
    if ($lowercase) {
      $transliterated = mb_strtolower($transliterated);
    }

    if (isset($replace_pattern) && isset($replace)) {
      if (!isset($replace_token)) {
        throw new AccessDeniedHttpException("Missing 'replace_token' query parameter.");
      }
      elseif (!$this->tokenGenerator->validate($replace_token$replace_pattern)) {
        throw new AccessDeniedHttpException("Invalid 'replace_token' query parameter.");
      }

      // Quote the pattern delimiter and remove null characters to avoid the e       // or other modifiers being injected.       $transliterated = preg_replace('@' . strtr($replace_pattern['@' => '\@', chr(0) => '']) . '@', $replace$transliterated);
    }
    return new JsonResponse($transliterated);
  }

}
    $access_result = $this->accessManager->checkRequest($request$this->account, TRUE);
    // Allow a master request to set the access result for a subrequest: if an     // access result attribute is already set, don't overwrite it.     if (!$request->attributes->has(AccessAwareRouterInterface::ACCESS_RESULT)) {
      $request->attributes->set(AccessAwareRouterInterface::ACCESS_RESULT, $access_result);
    }
    if (!$access_result->isAllowed()) {
      if ($access_result instanceof CacheableDependencyInterface && $request->isMethodCacheable()) {
        throw new CacheableAccessDeniedHttpException($access_result$access_result instanceof AccessResultReasonInterface ? $access_result->getReason() : '');
      }
      else {
        throw new AccessDeniedHttpException($access_result instanceof AccessResultReasonInterface ? $access_result->getReason() : '');
      }
    }
  }

  /** * {@inheritdoc} */
  public function getRouteCollection(): RouteCollection {
    return $this->router->getRouteCollection();
  }

  
try {
            $event->setResponse($this->startAuthentication($event->getRequest()$exception));
            $event->allowCustomResponseCode();
        } catch (\Exception $e) {
            $event->setThrowable($e);
        }
    }

    private function handleAccessDeniedException(ExceptionEvent $event, AccessDeniedException $exception): void
    {
        $event->setThrowable(new AccessDeniedHttpException($exception->getMessage()$exception));

        $token = $this->tokenStorage->getToken();
        if (!$this->authenticationTrustResolver->isFullFledged($token)) {
            $this->logger?->debug('Access denied, the user is not fully authenticated; redirecting to authentication entry point.', ['exception' => $exception]);

            try {
                $insufficientAuthenticationException = new InsufficientAuthenticationException('Full authentication is required to access this resource.', 0, $exception);
                if (null !== $token) {
                    $insufficientAuthenticationException->setToken($token);
                }

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