-1

I created a middleware/event subscriber to generalise a few security checks I need to perform on routes with a specific request attribute.

But in order to perform the required database query I need to get access to the authenticated user.

When I call $event->getRequest()->getUser() it always returns null even when the user is authenticated.

Where can I find more information about this?

And one more question: is using EventSubscribers a good practice for my needs?

Thanks in advance.

Dirk
  • 3,095
  • 4
  • 19
  • 37
  • You probably need to set your listener to lower priority so it will run after listener that propagates user information for application – Flying Jul 25 '19 at 12:01

2 Answers2

0

In https://stackoverflow.com/a/55417508/4707978 is the answer.

use Symfony\Component\Security\Core\Security;

class ExampleService
{
    private $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function someMethod()
    {
        $user = $this->security->getUser();
    }
}
Dirk
  • 3,095
  • 4
  • 19
  • 37
0

And one more question: is using EventSubscribers a good practice for my needs?

Probably not, you should check out security voters. With them you could implement your own custom security logic and enforce it with the given symfony tools like @IsGranted etc..

https://symfony.com/doc/current/security/voters.html

muffe
  • 2,285
  • 1
  • 19
  • 23