JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core

Introduction

 
This article covers exposing a central gateway point to the outer world to access protected API content. Handling of different micro-service routing will be done by Gateway itself.  
 

Journey of an HTTP request via Middleware Gateway to access multiple micro-services using .NET Core

 
For transmitting data securely from one endpoint to another endpoint, they are now digitally signed OR authenticated and it can be done in the form of token creation and propagating the same to validate it. For creating JWT based authentication there are ‘n’ numbers of tutorials in C# Corner.
 
You can filter a list of all JWT based work in .NET core.
 
As Microsoft brings the latest update for .NET core version into the market, similarly a code variation can be seen; so few topics for quick version difference is here,
In this article, we will learn how we can create custom route to connect multiple API(.net core microservices) from common middleware OR another name would be Gateway where we client(web/mobile/postman, etc..) call gateway/middleware as a central point all the time and respective routing to Microservices will be done by this common Gateway. Here, the Gateway work is handling routing to respective microservices, which is done internally.
 
For ease, we will be calling it a Gateway from now on, which guards and routes to respected microservice on the basis of the URL pattern.
 
Here, we will be creating 3 API’S (all are microservices)
  • Gateway API( Central Routing platform / API)
  • API/products/
  • API/customers/
And these both (2,3) are [Authorize] and should be accessible via the Common Gateway platform only with valid token else not.
 
So now we need a token. Right?
 
To create/generate a token concept is already explained in the above hyperlinks, go thoroughly before proceeding here. Note the above articles/ blogs explains only generate a token which works within single API call for [Authorize], So the question arises,
 
How do we connect multiple microservices with a common gateway & valid token?
 
Stay tuned and you will see step-by-step below.
 
For now, to create a Token, we need 1 more API (microservice). This API will be called a login API and is accessible anonymously. Right? Because you can only pass the username, password and get a valid token.
 
Now to summarize the above API structure, we will see it in pictorial representation below it will help you to generate an image of how it will work.
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core
If we try to read above image and convert it into the technical code part here are the steps we will do to see How we are identifying URL pattern & propagating token from common Gateway to which microservice.?
 
Before proceeding, let me share repository for this project attached above : Middleware.zip
 
Here we will see the folder structure of gateway and other microservices which will help you to correlate the above drawn image.
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core
 
As you can see, 2 *.bat file are placed. *.bat files are for quick starting microservices using the core CLI CMD for hosting them, as shown below:
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core
 
Similarly another one is for deleting /bin, /obj folder created while compiling. Handy stuff when you have multiple microservices and you want to clean them.
 
Since every microservice is hosted independently so to cross-check you can close all microservice CMD prompt window and open only API/customer I have separate *.bat file for each of them inside, Let see and try to run them via postman if you are authorized to get data. Let see it in action :
 
For api/customer service : we have 2 methods 1 is [Authorize] and another one is not
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core
 
Here the foremost thing is to get the Token so hit api/login, hosted on http://localhost:1234/ with the Username and Password as "admin" hardcoded you can replace it with your Database code later.
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core
 
Once you have token Ctrl+V here inside Bearer authorization and now try to access api/product URL you get the protected resource.
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core
 
Similarly, if you have an ‘n; number of microservices to handle all of them, exposing multiple URLs and managing is tough. And also we don’t want to expose directly our microservices to the outer world.
 
So to solve these types of situation we prefer common Gateway where routing redirection to multiple microservices is done by gateway and the client will only call gateway as 1 endpoint.
 
I hope you got the idea what we are trying to do here, So the following are the steps we do to identify routing URL with valid token via gateway as a central contact point.
 

Project Structure

  • Common.Utility : This is a common extension method utility for JWT token creation for below Projects.
  • Login_JWT : For Generating / Refreshing Token.
  • APIGatewayDemo : micro-service acting as a CENTRAL point of contact exposable to outer world.
  • CustomersAPIServices : Hosted micro-service. Not-Exposable to the outer world.
  • ProductsAPIServices : Hosted micro-service. Not-Exposable to the outer world.

Steps

  1. Inside Gateway: We create routes.json file which holds all microservices API destination URLs.
  2. For every URL call to Gateway will try to split and compare URLs with routes.json to reach destination microservice. (Hidden from outer world)
  3. After identifying which microservice to call we append Token in its request header and redirect to respective microservice.
  4. While landing in a microservice token is verified with the same key as we configured in app settings for all microservice. (Token verification is common for all microservices and it is done inside a startup.cs file)
  5. If the token is valid we get through and retrieve protected data.

Explanation

 
This file routes.json holds all URL’s at a central point, it is helpful in times of migration from 1 server to another, and minimizing human error due to central code.
 
Here we can also configure whether this API URL’s need authentication or not(helpful to avoid extra burden/ hoping to incase if your authentication is done at some other server and services are on different)
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core
 
Once you land in Gateway Project as shown in postman we are trying to get product/customer microservices but not directly. Via Gateway and internal routing is performed like this:
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core
 
Once we know by reading routes.json and some business logic which microservice to call, here we create new HTTP requests and append token in request header-based.
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core
 
To cross verify we have changed the key in appsettings.json file for api/customers now Token will not validate for customer but only for api/products. This process is done once you land in the startup.cs file of any microservice.
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core
 
For a valid token, protected data will be retrieved. Else error will be thrown. Have you tried to notice we are not using "api/" anymore; as it is now handled internally by the gateway to route to respected micro-service.
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core
 
For the case when we go to environment-specific (staging, production, etc...) we have files like appsettings.development.json which you can set from here:
 
JWT Token Routing From Gateway To Multiple Micro-Services In .NET Core 
 
For each micro-service hosted will have its own independent app settings environment specific file, And Common.Utility is the common place where TOKEN gets validated on the basis of Keys you have in your this setting file.
 
It has been generated from the same Key at the time of Login also and will remain intact for all services while validating as well.
 
That's how it works with some key concepts.
 
Feel free to ask question for any doubt. The sample project is uploaded.
 
See you!!