isGranted example

public function testIsGranted()
    {
        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $authorizationChecker->expects($this->once())->method('isGranted')->willReturn(true);

        $container = new Container();
        $container->set('security.authorization_checker', $authorizationChecker);

        $controller = $this->createController();
        $controller->setContainer($container);

        $this->assertTrue($controller->isGranted('foo'));
    }

    public function testdenyAccessUnlessGranted()
    {
        $this->expectException(AccessDeniedException::class);

        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $authorizationChecker->expects($this->once())->method('isGranted')->willReturn(false);

        $container = new Container();
        $container->set('security.authorization_checker', $authorizationChecker);

        
/** * Checks if the attribute is granted against the current authentication token and optionally supplied subject. * * @throws \LogicException */
    protected function isGranted(mixed $attribute, mixed $subject = null): bool
    {
        if (!$this->container->has('security.authorization_checker')) {
            throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
        }

        return $this->container->get('security.authorization_checker')->isGranted($attribute$subject);
    }

    /** * Throws an exception unless the attribute is granted against the current authentication token and optionally * supplied subject. * * @throws AccessDeniedException */
    protected function denyAccessUnlessGranted(mixed $attribute, mixed $subject = null, string $message = 'Access Denied.'): void
    {
        if (!$this->isGranted($attribute$subject)) {
            
if ($subjectRef = $attribute->subject) {
                if (\is_array($subjectRef)) {
                    foreach ($subjectRef as $refKey => $ref) {
                        $subject[\is_string($refKey) ? $refKey : (string) $ref] = $this->getIsGrantedSubject($ref$request$arguments);
                    }
                } else {
                    $subject = $this->getIsGrantedSubject($subjectRef$request$arguments);
                }
            }

            if (!$this->authChecker->isGranted($attribute->attribute, $subject)) {
                $message = $attribute->message ?: sprintf('Access Denied by #[IsGranted(%s)] on controller', $this->getIsGrantedString($attribute));

                if ($statusCode = $attribute->statusCode) {
                    throw new HttpException($statusCode$message, code: $attribute->exceptionCode ?? 0);
                }

                $accessDeniedException = new AccessDeniedException($message, code: $attribute->exceptionCode ?? 403);
                $accessDeniedException->setAttributes($attribute->attribute);
                $accessDeniedException->setSubject($subject);

                throw $accessDeniedException;
            }
/** * Define some ExpressionLanguage functions. * * @author Fabien Potencier <fabien@symfony.com> */
class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
    public function getFunctions(): array
    {
        return [
            new ExpressionFunction('is_authenticated', fn () => '$auth_checker->isGranted("IS_AUTHENTICATED")', fn (array $variables) => $variables['auth_checker']->isGranted('IS_AUTHENTICATED')),

            new ExpressionFunction('is_fully_authenticated', fn () => '$token && $auth_checker->isGranted("IS_AUTHENTICATED_FULLY")', fn (array $variables) => $variables['token'] && $variables['auth_checker']->isGranted('IS_AUTHENTICATED_FULLY')),

            new ExpressionFunction('is_granted', fn ($attributes$object = 'null') => sprintf('$auth_checker->isGranted(%s, %s)', $attributes$object)fn (array $variables$attributes$object = null) => $variables['auth_checker']->isGranted($attributes$object)),

            new ExpressionFunction('is_remember_me', fn () => '$token && $auth_checker->isGranted("IS_REMEMBERED")', fn (array $variables) => $variables['token'] && $variables['auth_checker']->isGranted('IS_REMEMBERED')),
        ];
    }
}


        return $token->getUser();
    }

    /** * Checks if the attributes are granted against the current authentication token and optionally supplied subject. */
    public function isGranted(mixed $attributes, mixed $subject = null): bool
    {
        return $this->container->get('security.authorization_checker')
            ->isGranted($attributes$subject);
    }

    public function getToken(): ?TokenInterface
    {
        return $this->container->get('security.token_storage')->getToken();
    }

    public function getFirewallConfig(Request $request): ?FirewallConfig
    {
        return $this->container->get('security.firewall.map')->getFirewallConfig($request);
    }

    

class ExpressionLanguage extends BaseExpressionLanguage
{
    /** * @return void */
    protected function registerFunctions()
    {
        parent::registerFunctions();

        $this->register('is_granted', fn ($attributes$object = 'null') => sprintf('$auth_checker->isGranted(%s, %s)', $attributes$object)fn (array $variables$attributes$object = null) => $variables['auth_checker']->isGranted($attributes$object));

        $this->register('is_valid', fn ($object = 'null', $groups = 'null') => sprintf('0 === count($validator->validate(%s, null, %s))', $object$groups)function Darray $variables$object = null, $groups = null) {
            if (!$variables['validator'] instanceof ValidatorInterface) {
                throw new RuntimeException('"is_valid" cannot be used as the Validator component is not installed. Try running "composer require symfony/validator".');
            }

            $errors = $variables['validator']->validate($object, null, $groups);

            return 0 === \count($errors);
        });
    }
}
$this->tokenStorage = new TokenStorage();

        $this->authorizationChecker = new AuthorizationChecker($this->tokenStorage, $this->accessDecisionManager);
    }

    public function testVoteWithoutAuthenticationToken()
    {
        $authorizationChecker = new AuthorizationChecker($this->tokenStorage, $this->accessDecisionManager);

        $this->accessDecisionManager->expects($this->once())->method('decide')->with($this->isInstanceOf(NullToken::class))->willReturn(false);

        $authorizationChecker->isGranted('ROLE_FOO');
    }

    /** * @dataProvider isGrantedProvider */
    public function testIsGranted($decide)
    {
        $token = new UsernamePasswordToken(new InMemoryUser('username', 'password', ['ROLE_USER']), 'provider', ['ROLE_USER']);

        $this->accessDecisionManager
            ->expects($this->once())
            


        return $token->getUser();
    }

    /** * Checks if the attributes are granted against the current authentication token and optionally supplied subject. */
    public function isGranted(mixed $attributes, mixed $subject = null): bool
    {
        return $this->container->get('security.authorization_checker')
            ->isGranted($attributes$subject);
    }

    public function getToken(): ?TokenInterface
    {
        return $this->container->get('security.token_storage')->getToken();
    }
}

        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);

        $authorizationChecker->expects($this->once())
            ->method('isGranted')
            ->with('SOME_ATTRIBUTE', 'SOME_SUBJECT')
            ->willReturn(true);

        $container = $this->createContainer('security.authorization_checker', $authorizationChecker);

        $security = new Security($container);
        $this->assertTrue($security->isGranted('SOME_ATTRIBUTE', 'SOME_SUBJECT'));
    }

    private function createContainer($serviceId$serviceObject)
    {
        $container = $this->createMock(ContainerInterface::class);

        $container->expects($this->atLeastOnce())
            ->method('get')
            ->with($serviceId)
            ->willReturn($serviceObject);

        

        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);

        $authorizationChecker->expects($this->once())
            ->method('isGranted')
            ->with('SOME_ATTRIBUTE', 'SOME_SUBJECT')
            ->willReturn(true);

        $container = $this->createContainer('security.authorization_checker', $authorizationChecker);

        $security = new Security($container);
        $this->assertTrue($security->isGranted('SOME_ATTRIBUTE', 'SOME_SUBJECT'));
    }

    /** * @dataProvider getFirewallConfigTests */
    public function testGetFirewallConfig(Request $request, ?FirewallConfig $expectedFirewallConfig)
    {
        $firewallMap = $this->createMock(FirewallMap::class);

        $firewallMap->expects($this->once())
            ->method('getFirewallConfig')
            

        $kernel = self::createKernel(['test_case' => 'SecurityHelper', 'root_config' => 'config.yml']);
        $kernel->boot();
        $container = $kernel->getContainer();

        // put a token into the storage so the final calls can function         $user = new InMemoryUser('foo', 'pass');
        $token = new UsernamePasswordToken($user, 'provider', ['ROLE_USER']);
        $container->get('functional.test.security.token_storage')->setToken($token);

        $security = $container->get('functional_test.security.helper');
        $this->assertTrue($security->isGranted('ROLE_USER'));
        $this->assertSame($token$security->getToken());
        $request = new Request();
        $request->server->set('REQUEST_URI', '/main/foo');
        $this->assertInstanceOf(FirewallConfig::class$firewallConfig = $security->getFirewallConfig($request));
        $this->assertSame('main', $firewallConfig->getName());
    }

    /** * @dataProvider userWillBeMarkedAsChangedIfRolesHasChangedProvider */
    public function testUserWillBeMarkedAsChangedIfRolesHasChanged(UserInterface $userWithAdminRole, UserInterface $userWithoutAdminRole)
    {
public function isGranted(mixed $role, mixed $object = null, string $field = null): bool
    {
        if (null === $this->securityChecker) {
            return false;
        }

        if (null !== $field) {
            $object = new FieldVote($object$field);
        }

        try {
            return $this->securityChecker->isGranted($role$object);
        } catch (AuthenticationCredentialsNotFoundException) {
            return false;
        }
    }

    public function getImpersonateExitUrl(string $exitTo = null): string
    {
        if (null === $this->impersonateUrlGenerator) {
            return '';
        }

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