Symfony how to use annotation @Security

Viewed 1071

I cant find any clear posts on how to use the annotation @Security of symfony. What are the parameters i can use? And most important, how can i secure a controller from guests and only accessible for users?

Currently i have

/**
 * 
 * @Route("/reseller/create/", name="app_reseller_create", methods={"POST", "GET"})
 * @IsGranted("ROLE_ADMIN")
     */
public function create(Request $request): Response
{
}
1 Answers

@IsGranted

If you only want to check if a user is logged in, you can use a special attribute instead of a role. For the full controller you must set it over the class definition.

/**
 * @IsGranted("IS_AUTHENTICATED_FULLY")
 */
class MyClass {

There are some special attributes that can use everywhere you can use ROLE_.

  • IS_AUTHENTICATED_FULLY is logged in.
  • IS_AUTHENTICATED_REMEMBERED is logged in or have an remembered cookie.
  • IS_AUTHENTICATED_ANONYMOUSLY any user have this
  • IS_ANONYMOUS only guests
  • IS_REMEMBERED only users with the rmembered cookie
  • IS_IMPERSONATOR only users that impersonating another user in the session.

The IS_ANONYMOUS, IS_REMEMBERED and IS_IMPERSONATOR attributes were introduced in Symfony 5.1.

@Security

The security annotation is more flexible as the IsGranted annotation and can use expressions.

Say you want a page, that only can be access if the user is an admin and have a specific token in his request.

  • with @IsGranted
/**
 * @IsGranted("ROLE_ADMIN", statusCode=404)
 */
 public function show(Request $request, Post $post) 
 {
     if (!$request->request->has('privatetoken') || 'mytoken' !== $request->request->get('privatetoken')) {
        return $this->createNotFoundException('not found');
     }

     // Show Post
 }
  • with @Security
/**
 * @Security("is_granted('ROLE_ADMIN') and request.get('privatetoken') == 'mytoken'", statusCode=404)
 */
 public function show(Post $post)
 {
     // Show Post
 }

With this, you must have an admin role and have an privatetoken parameter in your url like mydomain.com/post/show/?privatetoken=mytoken and you don't need the Request instance.

The expression has access to the following variables:

  • token: The current security token;
  • user: The current user object;
  • request: The request instance;
  • roles: The user roles;
  • and all request attributes.

There are too many possibilities to post this all. but i think it shows the difference to @IsGranted.

Symfony Docs

Related