How do I secure a Symfony2 REST API

1k views Asked by At

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

1

There are 1 answers

2
tomazahlin On BEST ANSWER

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