JIN
JIN

Reputation: 697

Should I put a user id in a REST url or get it from authentication

I'm building a RESTful api with Express.js. Let's say I have some Users which own Resources. A good way to get the Resources of a specific User would be: GET /users/:user_id/resources.

I implemented authentication for the API and can thus get the user_id from req.user.user_id instead of from the URL. This means I could just use GET /resources to get the resources from the authenticated user.

My question: is this good practice and why (or why not)?

Upvotes: 5

Views: 3314

Answers (2)

Prerak Jain
Prerak Jain

Reputation: 458

I think you are partially correct.

You are correct in the argument that one should not pass sensitive IDs like user_id as part of URI params. They should be derived from the JWT authentication token. While sensitive IDs are safe if you use HTTPS, it is still not recommended to pass them as URI params due to the following reasons -

  • they appear in your server logs so you don't want everyone who can access the logs to read the IDs being passed
  • they can appear in browser history which is even more worse

As far as the API URI path /resources is concerned, you can replace it with /user/resources which is a much more semantic way of addressing the resources of a user. Plain /resources would have a very different meaning.

Upvotes: 0

Sergey Yarotskiy
Sergey Yarotskiy

Reputation: 4804

I think, it is bad practice. Resources should return all resources, not filtered in any way. I would say it is better to have an additional endpoint /user/resources. In this way responses will be:

  1. /users/15/resources - will give resources for user 15 if allowed or 403.
  2. /user/resources - will give resources for the authenticated user (if I am user 15, then this gives the same response as in 1.) OR 404 OR 403.
  3. /resources - will give not filtered resources (if it is prohibited, then just don't create this endpoint, or return only public resources).

Upvotes: 2

Related Questions