In this guide, we will set up an API Gateway locally using Ocelot, configure local routing and authentication, and secure microservices using JWT authentication.
Why Use an API Gateway?
An API Gateway provides several advantages:
- Centralized Routing: Clients communicate with a single endpoint instead of multiple microservices.
- Security: Implements authentication, authorization, and rate limiting.
- Load Balancing: Distributes requests efficiently among services.
- Logging & Monitoring: Tracks request and response data.
- Protocol Translation: Converts between different communication protocols.
Prerequisites
Before we begin, ensure you have:
- .NET 8 SDK installed.
- Visual Studio 2022 or VS Code.
- Postman or any API testing tool.
- Basic knowledge of C# and ASP.NET Core.
Step 1: Install Ocelot API Gateway
Ocelot is a widely used open-source API Gateway for .NET applications. To install Ocelot, follow these steps:
1.1 Create an API Gateway Project
Open a terminal or command prompt and run:
mkdir MicroservicesWithGateway && cd MicroservicesWithGateway
Create a new ASP.NET Core Web API project:
dotnet new webapi -n APIGateway
cd APIGateway
1.2 Install Ocelot Package
Inside the APIGateway
project, install Ocelot via NuGet:
dotnet add package Ocelot
1.3 Configure Ocelot
Create a configuration file named ocelot.json
in the project root:
{
"Routes": [
{
"DownstreamPathTemplate": "/api/products",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 5001 }
],
"UpstreamPathTemplate": "/gateway/products",
"UpstreamHttpMethod": [ "Get" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5000"
}
}
This configuration routes http://localhost:5000/gateway/products
to http://localhost:5001/api/products
.
1.4 Modify Program.cs
to Use Ocelot
Open Program.cs
and update it as follows:
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOcelot();
var app = builder.Build();
await app.UseOcelot();
app.Run();
Run the API Gateway:
dotnet run
This starts the gateway at http://localhost:5000
.
Step 2: Configure Local Routing and Authentication
2.1 Create a Sample Microservice
To test routing, create a simple microservice.
dotnet new webapi -n ProductService
cd ProductService
Update Program.cs
:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/api/products", () => new[] { "Product1", "Product2" });
app.Run();
Run the service:
dotnet run --urls=http://localhost:5001
Now, visiting http://localhost:5000/gateway/products
through the API Gateway should proxy requests to http://localhost:5001/api/products
.
Step 3: Secure Microservices with JWT Authentication
3.1 Add Authentication to the API Gateway
Install authentication packages:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Update Program.cs
in APIGateway
:
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:5002";
options.Audience = "api_gateway";
});
builder.Services.AddAuthorization();
Modify appsettings.json
:
{
"Authentication": {
"JwtBearer": {
"Authority": "https://localhost:5002",
"Audience": "api_gateway"
}
}
}
3.2 Secure Microservices
In ProductService
, install JWT authentication:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Update Program.cs
:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://localhost:5002";
options.Audience = "product_service";
});
builder.Services.AddAuthorization();
3.3 Protect Endpoints
Modify the ProductService
endpoint:
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/api/products", (HttpContext httpContext) =>
{
if (!httpContext.User.Identity.IsAuthenticated)
return Results.Unauthorized();
return Results.Ok(new[] { "Product1", "Product2" });
}).RequireAuthorization();
3.4 Generate JWT Tokens (Example)
Use IdentityServer4 or another token provider to generate JWTs.
Alternatively, for testing, use a fake token provider like jwt.io
.
Testing the Setup
- Without Token: Access
http://localhost:5000/gateway/products
. It should return401 Unauthorized
. - With Token:
- Generate a JWT.
- Add
Authorization: Bearer <token>
in the request headers. - Now, the API Gateway should route requests successfully.
Conclusion
By following this guide, we have:
- Installed and configured Ocelot API Gateway.
- Set up local routing to microservices.
- Secured microservices using JWT authentication.
This setup ensures that microservices remain secure, scalable, and efficient while providing a seamless experience for clients. For production use, consider additional security layers like rate limiting, API keys, and logging.