Stefano Maglione
Stefano Maglione

Reputation: 4150

Undefined method isGranted in Symfony 4

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?

Upvotes: 1

Views: 1709

Answers (2)

hoover_D
hoover_D

Reputation: 650

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

Upvotes: 0

Barthy
Barthy

Reputation: 3231

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.

Upvotes: 2

Related Questions