Search code examples
sessionmicroservices

microservices session managing


As far as I know, the best practices in a microservices architecture are to not use shared DB/caches, so each microservice should have own database and cache database/mechanism. But what about the sessions?

Most peoples I found is proposing to use distributed session storage and as far as I understand distributed session storage means to have shared storage for sessions. But here is question number one. Should only API gateways verify the session or each microservice should verify the session? In other words, if frontend sends some request, should I only verify the session in the API gateway or in the each of microservice that API gateway communicating with?

Also, I heard, mostly in the videos on youtube from some conferences, that some teams using separate microservice to manage the session. But I can't find much information about that approach. Looks like it allows us to not share the session storage and manage it in one place as other storages in the microservices architecture. But I think it slows down the application as it adding communication overhead. I want to hear what do you think about this approach?


Solution

  • Sessions

    Modern applications need to be stateless so they can scale. When users are authenticated they are issued a token and every single request will carry that token (JWT token) along in request header. Normally token have expiry associated with them and Gateway can redirect to any application instance. Token carry along everything that they need to get authenticated.

    Validating the token/session

    You need to validate the session at Gateway and that's a preferred approach. But that really depends on your design. If you have services behind the api gateway and have any public access then surely token needs to be validated within each application/service . If your services are private then you can verify the token at Api Gateway only and reject non-verified requests.

    Native cloud Gateways(e.g. AWS Api Gatway) can validate the token without writing any additional code if you are using famous identity providers like (auth0 , Okta etc). If user claims are required then You may need to write a logic in your application or use the native libraries to get the user claims from token. I believe in this whole scenario you don't need any additional micro-service for Auth unless you want to write your own service to issue and validate tokens which in my opinion is not a good idea.