DEV Community

Cover image for Authentication between microservices - Part I
Suraj
Suraj

Posted on

Authentication between microservices - Part I

How to establish your own custom authentication between microservices?

What and Why? 🤔

Let's assume the interaction between 3 microservices.

  • User Service - Handles user's registration/login and other user data.
  • Product Service - Handles the product list present in the system.
  • Order Service- Handles Order, invokes product service to validate the order and invokes user service to attach required user-details to the order.

Why Authentication is needed?

Let's say you want to keep control over which service is calling another service.

Example here - User service shouldn't be calling order service or product service. And similarly, product service shouldn't be calling order service.

Explanation - Sometimes, a service ends up invoking an API of other services, which it should not (because that is not the service responsibility or may be to implement a new feature, etc).
Say, user-service starts invoking orders API of order-service to know if a user has placed order and wants to send an email to that user. And similarly, any other service can call this API of order-service.
But say, if we want to know, what all services call this order API, we won't be able to tell. To do this kind of tracing or to
restrict this type of API calls, order-service service should know from which service the call is originating.

  • But how will one service know, that it shouldn't allow any other service to use it's APIs except a few?

  • If you are using container orchestration like k8s, this could be achieved by using namespace restriction.

But how to do it independent of k8s?

Let's make one more assumption here:

  • Service A - Caller service
  • Service B - Called service i.e interaction happening from service A->B

For B to know if A is authorized to invoke its APIs, we can deploy one of the logics which is used for user authorization i.e sharing an authorization token while calling each API.

Now, who will own the generation of the authorization token?

  • Each caller service(service A) will generate a token (using a secret key) and pass to the called service (service B).

Note - Secret key that caller service (service A) uses to generate the token will also be present with called service (service B) for validation.

How the called service will validate the token it receives?

  • The called service(service B) will validate by decoding the token it received and comparing the secret key in the token with the stored secret key list.

How to implement it? Authentication between micro-services - Part II

If you enjoyed this story, please click the ❤️ button and share it to help others find it! Feel free to leave a comment below.

Top comments (0)