I am working on a Symfony 7 application where I need to implement fine-grained access control using security voters. Specifically, I want to grant access to an entire resource based on one set of rules, but restrict access to a specific property within that resource based on another set of rules. Despite my configuration attempts, I am encountering issues where my security voters are being called multiple times, and sometimes the object is not provided, leading to denied access.
I configured my User entity with access controls using #[ApiResource] and #[ApiProperty] annotations. My goal was to allow access to the entire resource if the user is an admin or the owner of the resource, while restricting access to the nom property to admins only. Here is the relevant part of my entity configuration:
php
#[ORMEntity(repositoryClass: UserRepository::class)]
#[ApiResource(
normalizationContext: ['groups' => ['read:user']],
denormalizationContext: ['groups' => ['write:user']],
operations: [
new Get(
security: "is_granted('VIEW', object)",
securityMessage: "Only the owner or an admin can access this resource."
),
new GetCollection(
security: "is_granted('ROLE_ADMIN')",
securityMessage: "Only an admin can access the collection."
),
new Post(
security: "is_granted('VIEW', object)",
securityMessage: "Only the owner or an admin can access this resource."
),
new Patch(
security: "is_granted('VIEW', object)",
securityMessage: "Only the owner or an admin can access this resource."
),
new Delete(
security: "is_granted('ROLE_ADMIN')",
securityMessage: "Only an admin can delete this resource."
)
]
)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
// other properties and methods...
#[ORMColumn(length: 255, nullable: true)]
#[Groups(['read:user', 'write:user'])]
#[ApiProperty(security: "is_granted('EDIT', object)", securityMessage: "Only an admin can view this property.")]
private ?string $nom = null;
// other properties and methods...
}
I expected that this configuration would call my custom voter once for the resource and once for the property. However, I observed that the voter is called multiple times, including calls where the object is not provided, resulting in access denial.
Note:
I am currently testing the functionality, so some of the access controls might not make practical sense. My primary goal is to understand how the security system works in this context. Thank you for your understanding.
Narvalhaut is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.