Search code examples
phpsymfonysymfony-security

How to implement security on a page shared by token on Symfony3


The need :

I need to share a "client" page for IS_AUTHENTICATED_ANONYMOUSLY users of my Symfony3 application.

What are the good practices to implement this kind of feature ?


My thoughts :

  1. Specific access control in security.yaml

    access_control:

    - { path: {regex with token?}, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    
  2. Token entity to store the token

  3. findOnBy with the token passed in url

    if(null === $token){
        throw new NotFoundHttpException('Page not found');
    }
    

Questions :

  1. The regex is not working what would be a corresponding regex for case/{token} ?
  2. I have the feeling that this method works but is not very effective in terms of security requirement. Is my idea sufficient to manage security on this feature ? What would be a better practice ?

Solution

  • Move the authentication outside of your controller, and return a proper "not authorized" exception if the token is not valid.

    Basically you will need to create an implementation of AuthenticatorInterface, which is usually accomplished by extending AbstractGuardAuthenticator as described here.

    In your supports() method you will likely check the existence of that token, and probably that the route is the one you really want to protect/authenticate.