Symfony – Voter returns null object on /GET LIST

I’m working with Symfony5 and ApiPlatform with JWT implemented on the app.

I have a classic /GET route, that returns only few field of all User entities by adding the dynamic group "anonym:read" to some property for unauthenticated users through a ContextBuilder.

As the user don’t need to have a JWT token, I’ve added this to the access_control part of my security.yml file :

access_control:
  - { path: ^/users, roles: IS_AUTHENTICATED_ANONYMOUSLY }

This route is also used by other kind of users with different authorization, so it passes through a Voter.

And the voter is where I block, the list of object I’m supposed to receive in $subject variable end up being null, returning false from the support function of the voter and so denying access.

And if I withdraw the security constraint from the /GET route annotation, I do receive the list of User I want with only the desired fields.

I don’t manage to figure out why the $subject is null for this list of object.

User.php:

/**
 * @ApiResource(
 *     attributes={
 *          "normalization_context"={"groups"={"user:read", "user:list"}},
 *          "denormalization_context"={"groups"={"user:write"}},
 *          "order"={"availabilities.start": "ASC"}
 *     },
 *     collectionOperations={
 *          "get"={
 *              "mehtod"="GET",
 *              "security"="is_granted('LIST', object)",
 *              "normalization_context"={"groups"={"user:list"}},
 *          },
 *          "post"={
 *              "method"="POST",
 *              "security_post_denormalize"="is_granted('POST', object)",
 *              "denormalization_context"={"groups"={"user:write"}}
 *          }
 *     },
 *     itemOperations={
 *          "get"={
 *              "method"="GET",
 *              "security"="is_granted('ROLE_USER')"
 *          },
 *          "put"={
 *              "method"="PUT",
 *              "security"="is_granted('PUT', object)"
 *          },
 *          "delete"={
 *              "method"="DELETE",
 *              "security"="is_granted('ROLE_ADMIN')"
 *          }
 *     }
 * )
 * @ORMEntity(repositoryClass=UserRepository::class)
 */
class User
{

    /**
     * @ORMId
     * @ORMGeneratedValue
     * @ORMColumn(type="integer")
     * @Groups({"user:read", "user:list"})
     */
    private $id;

    /**
     * @ORMColumn(type="boolean")
     * @Groups({"user:read", "user:list", "user:write", "anonym:read"})
     */
    private $active;

    /**
     * @ORMColumn(type="string", length=255, nullable=true)
     * @Groups({"user:read", "user:list", "user:write", "anonym:read"})
     */
    private $photo;

    /**
     * @ORMColumn(type="text")
     * @Groups({"user:read", "user:list", "user:write"})
     */
    private $description;

}

UserContextBuilder.php:

final class UserContextBuilder implements SerializerContextBuilderInterface
{
    private $decorated;
    private $authorizationChecker;

    public function __construct(SerializerContextBuilderInterface $decorated, AuthorizationCheckerInterface $authorizationChecker)
    {
        $this->decorated = $decorated;
        $this->authorizationChecker = $authorizationChecker;
    }

    public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array
    {
        $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
        $resourceClass = $context['resource_class'] ?? null;

        if (
            $resourceClass === User::class && isset($context['groups']) &&
            !$this->authorizationChecker->isGranted('ROLE_USER') &&
            true == $normalization
        ) {
            $context['groups'][] = 'anonym:read';
        }

        return $context;
    }
}

UserVoter.php:


class UserVoter extends AbstractVoter
{
    protected function supports($attribute, $subject)
    {
        return parent::supports($attribute, $subject) &&
            ($subject instanceof User ||
                $this->arrayOf($subject, User::class));
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        /** @var User $user */
        $user = $token->getUser();

        if ($this->accessDecisionManager->decide($token, [GenericRoles::ROLE_ADMIN])) {
            return true;
        }

        switch ($attribute) {
            case Actions::LIST:
                return $user->hasRole(GenericRoles::ROLE_USER) || !$user instanceof User;
            case Actions::PUT:
                return ($user->getId() == $subject->getUser()->getId() ||
                        $user->hasRole(GenericRoles::SOME_SPECIAL_ROLE));
            case Actions::POST:
                return $user->hasRole(GenericRoles::SOME_SPECIAL_ROLE);
        }

        return false;
    }
}

If anyone has any idea on why this happens, I’d be gratefull

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *