Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the IsGranted annotation with a string as subject?

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?

like image 273
Evert Avatar asked Oct 16 '25 12:10

Evert


2 Answers

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 ;)

like image 80
Pinks Not Dead Avatar answered Oct 18 '25 15:10

Pinks Not Dead


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

like image 21
Gildas Avatar answered Oct 18 '25 13:10

Gildas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!