Search code examples
restwebwebservertokenjwt

REST api - How should the client supply userid to the request URL for its user resource?


A client needs to login with a username/password the first time. A JWT token is returned for future requests. The token will have a userid so that the server can fetch the user's resource from the database.

The problem I have is the client needs to form the request URL to update its resource let's say POST /users/{userid}. How should I get the userid for the client? I can't access the JWT token which is stored in a httpOnly secure cookie. Should I store the userid on the client somehow? So that it can use it for the URL?


Solution

  • I see your problem now. You are afraid of losing some of the advantages of a RESTFUL api, a unique resource locator,

    I often have a set of URIs that start with the path that indicates that operations are on the currently authenticated user.

    /current/profile
    /current/blog_posts
    

    In such cases I pull the user out of the request context on the server, which I can get by parsing the JWT token.

    And when I want to operate on other users I use the identifier instead

    /{{user_id}}/profile
    /{{user_id}}/blog_posts
    

    I'm not sure whether this is strictly RESTFUL, but it does give users of my API a stable and discoverable URI. I've used this pattern with a number of projects and teams without complaint.

    If you really must get a user identifier two ideas idea comes to mind:

    • Return the user_id along with the jwt token.
    • Make an extra API call to get the user_id from the server and then use that for all subsequent calls.

    Oh, another option comes to mind. Change your notion of a user_id and use the username (which you already have) instead.