0

I use the security.yml with access_control to secure the API paths based on the user role. This works fine, but how do I secure specific parameters like /api/project/:id? Different users have access to different project ids. Therefore a database call has to be made to check if this user has access to this project.

I tried to use $this->denyAccessUnlessGranted('GET', $projectId, 'Unauthorized access!'); in the ProjectController, which calls a custom Voter to check the database and therefore the access.

public function getProjectAction(Request $request, $id)
{
    $this->denyAccessUnlessGranted('GET', $id, 'Unauthorized access!');

This works, but it seems very unpractical to add this code to 10+ actions in the ProjectController alone and also in many parts of the API.

Therefore my question: What is the best pratice to secure a REST api with symfony2, fosUserBundle and fosRestBundle

3
  • symfony.com/doc/current/cookbook/event_dispatcher/… or symfony.com/doc/current/cookbook/service_container/… Commented Jun 16, 2015 at 17:32
  • You would suggest to create an interface and an event listener, check the $id access in the event listener and deny the request if the access is not granted. Is this correct? Commented Jun 17, 2015 at 6:02
  • Basically. The listener uses the security context to check the user permissions. The security context will be using your voter. The point is that the listener will run before your controller so no need for the controller to check. Commented Jun 17, 2015 at 14:42

1 Answer 1

2

I would suggest introducing security voters.

http://symfony.com/doc/current/cookbook/security/voters_data_permission.html

Also create some kind of exception handler / listener, to catch your exceptions and make a specific error response.

http://symfony.com/doc/current/cookbook/service_container/event_listener.html

Sign up to request clarification or add additional context in comments.

2 Comments

As written in my original question: this is the approach I use right now, but it seems very unpractical since I have to call the voter in each function. There must be a better way?
I believe this is one of the responsibilities of the controller classes. Even if you delegate this responsibility to some other class with a wider understanding of how the part of the system works, you will still end up using it more or less the same amount of times. Also the documentation shows an example of how to use it in a controller class. I also did it like this on a project in the past and I had no problem with maintainability. I believe you are then on a correct way. You could also look into ParamConverters and check BASIC (permission to load... etc) things in there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.