Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Forbidden Response in Symfony2?

Tags:

php

symfony

I just discovered SensioLabsInsight and found very interesting tips on how to write good code. It would be great if there was some explanation on why (or why not) something should be used - even for basic stuff like exit and die. It would help me to explain things to people I work with.

So my question is specifically for AccessDeniedHttpException - it says:

Symfony applications should not throw AccessDeniedHttpException

So how do I return 403 Forbidden from the application controller or EventListener?
What is the best practice?

To be honest I thought it would be

throw new AccessDeniedHttpException()

Since for 404 you have

throw $this->createNotFoundException()

But it looks like I was wrong.

like image 663
Janusz Slota Avatar asked Jul 23 '13 09:07

Janusz Slota


2 Answers

I think it means that you must throw AccessDeniedException instead of directly throwing AccessDeniedHttpException.

Main reason is that AccessDeniedException is catched by the event listener in Symfony\Component\Security\Http\Firewall\ExceptionListener and then you can make some stuff with it. Check onKernelException function.

like image 55
Alexey B. Avatar answered Nov 17 '22 05:11

Alexey B.


That sentence has to be considered with the whole architecture of Symfony in mind.

In the Symfony framework there is a whole subsystem devoted to security applying the 2 step Authentication + Authorization process. That said in the architecture of Symfony the Controllers, that are what basically the framework leaves to you to develop and so they are "the application", will be called only if the Authentication + Authorization has been passed.

So that sentence say that you should not need to throw that Exception becouse that is the work for the Security component. Doing that it is not forbidden or even made impossible but it is not the way which the framework has been normally thinked to work.

This can happen in two situations:

  1. Your application is particular and you need to do that way
  2. You are doing the security work out of the framework way of doing. It is your choice, just evaluate cost/benefits of not using the framework features and write your own ones.
like image 4
Diego Mazzaro Avatar answered Nov 17 '22 05:11

Diego Mazzaro