Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I throw a 403 exception in Symfony2?

I am doing a check if there is a specific token in my request URI and throw a Symfony\Component\Security\Core\Exception\AccessDeniedException if there is no token or the token is wrong.

if(!isset($token) && $token != 'whatever') {   throw new AccessDeniedException('No token given or token is wrong.'); } 

But when I use this AccessDeniedException, Symfony2 simply redirects to the login page. Instead, I would like to have a dedicated 403 error page (I already created app/Resources/TwigBundle/views/Exceptions/error403.html.twig file).

What would I have to change in order to achieve this? Do I have to use a PHP native Exception? But how can I tell to pass a 403 error code?

Does Symfony2 maybe have a specific 403-Exception which doesn't simply redirect to login?

like image 876
Gottlieb Notschnabel Avatar asked Feb 21 '14 10:02

Gottlieb Notschnabel


People also ask

How does Symfony handle the 403 Forbidden error?

Symfony will handle this exception and generates a response based on the authentication state: If the user is authenticated, but does not have the required permissions, a 403 Forbidden response is generated.

How do I bypass the security system in Symfony?

Throw Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException. That will bypass the security system and give you a 403 response which in turn will get picked up by the twig exception listener.

What is an Access Denied page in Symfony?

This is the access denied page. It means that we are authenticated, but don’t have access. Of course in Symfony’s prod environment, we’ll be able to customize how this looks. We’ll cover how to customize error pages in the next episode. The access_control section of security.yml is the easiest way to control access, but also the least flexible.

What is accessdeniedexception in Symfony?

1) AccessDeniedException is a very special exception. When you throw it, it triggers the part of Symfony that tries to get the user to login (usually by redirecting them to /login).


Video Answer


2 Answers

Throw Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException.

That will bypass the security system and give you a 403 response which in turn will get picked up by the twig exception listener.

like image 191
Cerad Avatar answered Oct 06 '22 04:10

Cerad


As of Symfony 2.6 you can use the following controller shortcut that will trigger the good exception for you:

return $this->denyAccessUnlessGranted('ROLE_EDIT', $item, 'You cannot edit this item.'); 
like image 27
COil Avatar answered Oct 06 '22 04:10

COil