Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing User-Id in Client Side App for API Request

I have a Node-Express REST API where I can make a GET request to a user controller - /users/:id - where :id is the user-id number stored in the database. I also have a React-Redux client side app that makes a call to the API. In order to make the request, the client app needs access to the user-id, but I’m currently not sure of the best way to store the user-id on the client side.

For additional context, my API sends to the client a JWT token on login that holds the user-id; the client app saves the token in localStorage. When the client makes a request, the API verifies that the user-id in the decoded token matches the Id contained in the URL before sending a response back to the client.

I see two potential solutions:

  1. Decode the JWT token on the client and use the user-id stored in the token to make the API call. I think this is a potential security risk, since I believe I would need to store the secret on the client app. Also, anyone who has the token can gain access to the user’s information.
  2. API sends the user-id on authentication, and the client stores it in localStorage. (I don’t think storing it in the Redux store would work since the user could refresh, clearing state of the user-id). My sense is that this is not best practice, since I don’t see many other client side apps taking this approach.

Which one of the two is a better solution, or is there another approach that I'm not considering?

like image 611
Anup Sheth Avatar asked May 13 '17 20:05

Anup Sheth


1 Answers

You're right about option #1. Never decode the token client-side. That would require the client-side code to know the "secret", which would expose it to anyone looking through your Javascript.

Option #2 is good, assuming that you still send the token with every request for security purposes. For storage, yes you have to store it in a cookie or in localStorage, or as you say it will be lost on refresh.

To get the ID in the client-side code, have your client-side code read it from the cookie / localstorage. There are libraries for that; react-cookie reads cookies, for example. Either you can do that every time you need to access it, or you can read it once during the initial page load, and then dispatch it into the Redux store.

like image 87
stone Avatar answered Oct 23 '22 14:10

stone