Chinmay
Chinmay

Reputation: 4882

Symfony security - get details on Access Denied

If i have a controller method protected with say is_granted('ROLE_XYZ'), and the user does not have that role, how do I get hold of "ROLE_XYZ" in the exception? Currently, the exception message just has "Access Denied".

Or, in general, I want to know which expression failed.

Upvotes: 1

Views: 841

Answers (1)

Alexis
Alexis

Reputation: 377

Hum I'm not sure I understand your question correctly.

But if you want to create a custom Access Denied Exception with a custom message, have a look at this page: https://symfony.com/doc/current/security/access_denied_handler.html

Hope it helps

EDIT: In case the previous given link is broken, to create a custom message you have to:

  • Create a class which implements AccessDeniedHandlerInterface
class AccessDeniedHandler implements AccessDeniedHandlerInterface
    {
        public function handle(Request $request, AccessDeniedException $accessDeniedException)
        {
            // ...

            return new Response($content, 403);
        }
    }
  • Then modify your security.yaml to add your custom class
    # config/packages/security.yaml
    firewalls:
        # ...

        main:
            # ...
            access_denied_handler: App\Security\AccessDeniedHandler

Upvotes: 1

Related Questions