Symfony2 and FOSRestBundle - Only Allow Users to Edit Data That They Own

163 Views Asked by At

Symphony Version 2.2 (yah, I know). FOSRestBundle: 1.5.3

Current Scenario

I have a REST Api driving an angular page. Let's say that each user has a token associated w/ their user record. Consider the following Urls.

  • GET /api/user/{token}/messages
  • POST /api/user/{token}/messages
  • GET /api/messages/{messageId}

  • GET /api/user/{token}/votes

  • POST /api/user/{token}/votes

So the user can GET and POST messages. The user can make votes and see them.

(I have about 30 diff routes like this - the URLs are all over the place).

Question

How can I verify that the user is allowed to GET/POST data for the token they're providing?

I do realize I could copy/paste some code to check the given user vs the user from the URL. Or I could write a service w/ a checkUser() function on each endpoint.

My hope, though, is that there is some way of doing this that doesn't require me to check the user on each endpoint's entry point.

2

There are 2 best solutions below

0
On

i would create a before filter and add the checkUser() hook in there , that way you don't have to check the user permission on each endpoint

example

0
On

Don't send the authentication in the Endpoint. An endpoint typically should be Idempotent, and should individually identify a particular resource.

Send your authentication tokens in HTTP headers.

With that said, as a strategy, baking in your security using @wonde is a good idea. I have implemented a custom base controller class in the past, but the filter and event handling built into symphony provides an even sexier solution.