Microservices session data when communicating internally

authenticationauthorizationmicroservicesservices

I'm not sure the title is correct, so please advise if you think of a better title.

The scenario is:

  1. We have an API gateway that exposes REST API to our clients (web and
    mobile apps).
  2. We have a "sessions" microservice that keeps track of
    the logged in users. When a user logs in, a new session is stored in
    this microservice, and for each request that requires
    authentication, the API GW first communicates with this microservice
    to validate the session token and get session related information
    (user id, permissions list etc.)
  3. The API GW after validating the
    session performs some calls to other microservices that are required
    to fulfill the request, but some of them needs the logged in user
    ID.

A simple example is a blogs website, where the logged in user wants to add a post to his blog.

  1. Performs a POST to /posts with his new blog post and the session token (unique session ID)
  2. The request reaches the API GW.
  3. The API GW checks the session token against the sessions microservice that validates the token and returns the session data (user id, permissions)
  4. The API GW now need to send a request to the posts microservice to add the post to the user.

The question is about the 4th step – what would be considered a better practice:

  • Sending the user ID as part of the post object, meaning, the post service does not handle any authentication / autharization, it simply stores the object after basic validation of the object.

    OR

  • Using some sort of JWT that contains the sessions information and pass it with the blog post to the posts service, that must then validate the JWT and use the user ID from the JWT when storing the post data that was passed without any user ID in it?

Best Answer

Use Both.

First, JWT should not be used to replace your client-side session. They were made to solve a different problem. For more details visit the reference link.

Reference Link http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/

I had the same question a while ago. The way I solved my problem was the following:

Store the sessions on the backend (High Available Key-value store with constant time complexity O(1) ) and use the JWT to store the user id or the session id so you can retrieve in the backend.

This link has an interesting implementation. https://sequoia.makes.software/session-management-with-microservices/

There are a couple of variations to this. The main concept to remember is to use the right tools for the job and TRY to keep it simple.