4

I am currently playing with NestJS' microservices and authentication, and I am facing a problem for which I don't have a clear solution.

Let's imagine I have an API gateway balancing the calls to multiple microservices. I would like to enable authentication (via JWT tokens) and retreive the user information for every process I might call on any microservice.

The problem I am facing is that I don't know where to decode the token.

  • Should the API gateway decode the token and proxy the HTTP request to the microservice by appending the user data to it ?
  • Should the end microservice decode the token instead of the gateway ?

I feel confident implementing both of them, I just cannot figure out if they are good practicesor if there is a better solution I haven't thought of yet.

1 Answer 1

7

The best way to do this by use the flow in below.

  1. Request go from client to API gateway.
  2. API gateway will call auth microservice to decode the token.
  3. Auth microservice will verify this token and decode it. then call db to get user data then send user data to API gateway.
  4. Now API gateway have the user data. then will inject headers like x-user-id, x-user-name, x-user-email. and call microservice-x.

Lets say microservice-x will create and record in table then call microservice-z to send email.

  1. Microservice-x will receive request to create record in table for user id x-user-id. then call microservice-z to send email by x-user-email.

enter image description here

4
  • Thank you for your answer. So in this way, if I pass the user ID through microservices, they should ask the database for the full user data ?
    – KSR
    Commented Jul 20, 2020 at 20:46
  • Yes, Auth Microservice will receive token then check if it valid and decode it then call db to get user date. becouse token should have only user uuid. so you will call db to get anther data like x-user-email , x-user-name. Commented Jul 20, 2020 at 20:50
  • My question was more like: let's say microservice X needs to retreive an object representing the user, would it be a good practice to let this microservice X ask the database for the user entity, or could it be passed by the API Gateway directly ?
    – KSR
    Commented Jul 20, 2020 at 20:56
  • 1
    its depends on what is user data you need. let's say you need uuid,name,email. you will use headers. but if you need many details you will call database or user microservice again to get this data by uuid. Commented Jul 20, 2020 at 21:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.