1

I am using a statement from a Symfony2 app in Symfony4:

$securityContext = $this->container->get('security.token_storage');         
if($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') ){
. . .
}

I get always error:

Attempted to call an undefined method named "isGranted" of class "Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage

what I am missing?

Stefano Maglione
  • 3,946
  • 11
  • 49
  • 96

2 Answers2

2

Symfony gives you several ways to enforce authorization, including […] using isGranted on the security.authorization_checker service directly.

source

You should call isGranted on the security.authorization_checker service, not the security.token_storage.

Barthy
  • 3,151
  • 1
  • 25
  • 42
0

for SF4, according to the docs:

public function hello($name)
{
    $this->denyAccessUnlessGranted('IS_AUTHENTICATED_REMEMBERED');

    // ...
}

You have to use security.authorization_checker service. And the code above is the same as:

public function hello($name, AuthorizationCheckerInterface $authChecker)
{
    if (false === $authChecker->isGranted('ROLE_ADMIN')) {
        throw new AccessDeniedException('Unable to access this page!');
    }

    // ...
}

check docs here https://symfony.com/doc/4.0/security.html#securing-controllers-and-other-code

hoover_D
  • 620
  • 4
  • 9