Authentication & Authorization in microservices architecture.

Khizer Younas
5 min readDec 21, 2019

--

Courtesy of undraw.co

Imagine that you and your team has build an amazing application and you are serving real people’s problem on top of that you are constantly adding new features to improve this application even better. But now you have come at a stage were complexity of your application has grew so much that you can not managing this much code in monolithic world which is tightly coupled together can no longer fulfil your application’s needs or your application has become so popular that you can no longer scale vertically. After much consideration you and your team has decided to go with the microservices architecture.

What is microservices architecture?

Microservices are a software development technique — a variant of the service-oriented architecture (SOA) structural style — that arranges an application as a collection of loosely coupled services. In a microservices architecture, services are fine-grained and the protocols are lightweight.

Problem solved, right?

Actually no, migrating to microservices architecture is not as simple as separating your application’s features into loosely coupled services the application starts at the first step authentication & authorization. Authentication and authorization is the first part of building any application and we all (the developers) have been implementing this from the dawn of internet, and it all worked fine in our monolithic world. We authenticate a user with his/her credentials get a token back and make request to our server with the auth token our server checks the validity and sends our resource back.

But now in microservice architecture what happens if we send a request to service A which needs to get data from service B how service B is going to authenticate if the request sent is valid.

We can build an auth service that will take care of our authentication (AuthN) and authorization (AuthZ) part to mitigate identity problem but by doing this we have created another bottle neck which is actually our auth service. Every request user to service or service to service will now call auth service first then execute which means our auth service is going to be very busy plus every request to our auth service is going to be blocking and over some protocol i.e. HTTP, hence expensive.

How to solve this issue?

One way is to build an auth server that can issue tokens when ever user needs and those tokens can be validated without the following.

  • Calling the auth service for every request to validate the identity.
  • Replicating authN and authZ code in every service which actually kills the purpose of microservices.

JSON Web Tokens or commonly known as JWT is the best technology for this case to be handled.

What is JWT? Official JWT introduction is the most helpful resource for it.

JWT is signed with HS256 algorithm which takes a secret key (generally a long random string) for signing and verifying by default, which making cross service verifying hard. But It also provides RS256 algorithm which works with RSA Key pairs.

We can signs the token with RSA private key and other services can verify the identity using RSA public key.

Technicality of JWT

  1. The server verifies if the user is legit and responds with a token (JWT) containing the identity of the user signed with RSA private key.
  2. Whenever a user makes a request to any service or service makes a request to another service this token is passed as a metadata which is first verified at the service itself with RSA public key. If the verification process is successful then resource is returned with status code 200 otherwise status code 401 or 403 is responded.
Courtesy of undraw.co

Now we know how can we handle AuthN & AuthZ in microservices let’s build a simple auth service implementation.

Technologies used

  • NodeJS

Create a NodeJS project

Create a folder with name i.e. auth-deputy and open your terminal to initiate simple nodejs project and install dependencies. There are many npm packages for JWT but we are going to use jsonwebtoken npm package by Auth0.

$ cd <project-path>/auth-deputy/
$ npm init -y
$ npm install -s jsonwebtoken node-rsa

With dependencies installed we can move towards coding part.

Creating RSA key pair

The first part is get RSA key pair for signing and verifying our tokens. Create a file named rsa-generator.js and paste the following code to get the key pair.

const NodeRSA = require("node-rsa");
const key = new NodeRSA({ b: 512 });
let keypair = {
private: key.exportKey(),
public: key.exportKey("public")
};
console.log(keypair);

Creating a JWT script

You can sign a token with the following code.

const jwt = require("jsonwebtoken");let obj = { "id": 1, "username": "mkhizeryounas" };
let privateKey = <rsa-private-key>;
obj["access_token"] = jwt.sign(obj, privateKey, { algorithm: "RS256" });console.log("User", obj);

Verifying your token can be done in any microservice with the following code.

const jwt = require("jsonwebtoken");jwt.verify(<JWT-Token>, <rsa-public-key>, { algorithm: "RS256"}, function(decoded, err) {
if(err) throw err;
console.log("Verified token", decoded);
});

This article should get you started with the AuthN and AuthZ implementation in your microservice architecture and I hope it has answered some of the first questions that you had when you started thinking about this problem.

AuthDeputy Identity Server

I have also prepared an auth server using nodejs, mongodb, angularjs called AuthDeputy. This is an opensource identity management service that can be used in any microservices architecture. This has the following features.

  • Scope management
  • Permission (roles) management
  • User management
  • Realm config (Token expiry)
  • HTTP Protocol
  • AuthZ validator endpoint
  • RESTful API
  • Single sign-On (SSO)

TODO: gRPC implementation.

This project is available on GitHub under MIT Opensource Licence so feel free to use it in your next project and open PRs.

AuthDeputy dashboard screenshot
AuthDeputy new permissions group screenshot

Also see

These are some other identity services worth checking out.

Also read

--

--

No responses yet