AuthorizationChecker example

class AuthorizationCheckerTest extends TestCase
{
    private MockObject&AccessDecisionManagerInterface $accessDecisionManager;
    private AuthorizationChecker $authorizationChecker;
    private TokenStorage $tokenStorage;

    protected function setUp(): void
    {
        $this->accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class);
        $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 provider */
    public function testIsAuthenticated($token$expression$result)
    {
        $expressionLanguage = new ExpressionLanguage();
        $trustResolver = new AuthenticationTrustResolver();
        $tokenStorage = new TokenStorage();
        $tokenStorage->setToken($token);
        $accessDecisionManager = new AccessDecisionManager([new RoleVoter()new AuthenticatedVoter($trustResolver)]);
        $authChecker = new AuthorizationChecker($tokenStorage$accessDecisionManager);

        $context = [];
        $context['auth_checker'] = $authChecker;
        $context['token'] = $token;

        $this->assertEquals($result$expressionLanguage->evaluate($expression$context));
    }

    public static function provider()
    {
        $roles = ['ROLE_USER', 'ROLE_ADMIN'];
        
Home | Imprint | This part of the site doesn't use cookies.