I find it really handy that in Symfony I can use annotations to add extra functionality to my controller methods in a clean way. Like this for example:
/**
* @Route("/{id}")
* @IsGranted("view", subject="product")
* @return Response
*/
public function view(Product $product)
{
dump(compact('product'));
return new Response('It worked!');
}
However, for the create method, I don't have a product instance, so I'd like to use the @IsGranted
annotation with as the subject the string "App\Entity\Post". I hoped I could do that like this:
/**
* @Route("/")
* @IsGranted("create", subject=Product::class)
* @return Response
*/
public function create()
{
return new Response('Did it work?');
}
But unfortunately I get the following error: Could not find the subject "App\Entity\Product" for the @IsGranted annotation. Try adding a "$App\Entity\Product" argument to your controller method.
So @IsGranted
is still under the impression that it's supposed to look for a method parameter with the name $App\Entity\Product
. Is there a way I can use it with just a string literal?
Another way:
class AnotherController extends AbstractDashboardController
{
public function index(): Response
{
$this->denyAccessUnlessGranted('MY_VOTER', 'my_variable');
//...
}
}
unlike the 'IsGranted' annotation, method 'denyAccessUnlessGranted' takes string easier ;)
Can't you just omit the subject attribute?
I haven't used the annotation but I know that Symfony auth checker allows to call "isGranted" without a subject.
See example here: https://symfony.com/doc/current/security.html#securing-controllers-and-other-code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With