Tuesday, October 7, 2025

🔑 Example: Ocelot API Gateway with JWT Authentication

 

1️⃣ Create Solution Structure

We’ll create 3 projects:

  1. AuthService → issues JWT tokens.

  2. ProductService → sample microservice.

  3. ApiGateway → Ocelot API Gateway.

dotnet new webapi -n AuthService dotnet new webapi -n ProductService dotnet new webapi -n ApiGateway

2️⃣ Implement AuthService (JWT Token Issuer)

Install NuGet packages

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer dotnet add package System.IdentityModel.Tokens.Jwt

Add Token Generation (AuthController.cs)

using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; [ApiController] [Route("api/[controller]")] public class AuthController : ControllerBase { [HttpPost("login")] public IActionResult Login(string username, string password) { // Simple validation (replace with real DB check) if (username == "admin" && password == "password") { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes("SuperSecretKeyForJwt123456"); // store securely in secrets manager var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim("role", "Admin") }), Expires = DateTime.UtcNow.AddMinutes(30), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return Ok(new { token = tokenHandler.WriteToken(token) }); } return Unauthorized(); } }

3️⃣ Implement ProductService (Protected Microservice)

Add a Controller (ProductsController.cs)

using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { [Authorize] [HttpGet] public IActionResult GetProducts() { return Ok(new[] { new { Id = 1, Name = "T-shirt", Price = 499 }, new { Id = 2, Name = "Jeans", Price = 999 } }); } }

Configure JWT Authentication in Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; var builder = WebApplication.CreateBuilder(args); var key = Encoding.ASCII.GetBytes("SuperSecretKeyForJwt123456"); builder.Services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); builder.Services.AddControllers(); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();

4️⃣ Configure API Gateway (Ocelot)

Install Ocelot

dotnet add package Ocelot dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Add ocelot.json

{ "Routes": [ { "DownstreamPathTemplate": "/api/products", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5002 } // ProductService port ], "UpstreamPathTemplate": "/products", "UpstreamHttpMethod": [ "Get" ], "AuthenticationOptions": { "AuthenticationProviderKey": "TestKey", "AllowedScopes": [] } } ], "GlobalConfiguration": { "BaseUrl": "https://localhost:5000" } }

Configure Program.cs in ApiGateway

using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using Ocelot.DependencyInjection; using Ocelot.Middleware; using System.Text; var builder = WebApplication.CreateBuilder(args); var key = Encoding.ASCII.GetBytes("SuperSecretKeyForJwt123456"); builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer("TestKey", x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); builder.Services.AddOcelot(); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); await app.UseOcelot(); app.Run();

5️⃣ Test Flow

  1. Get Token

    POST https://localhost:5001/api/auth/login Body: { "username": "admin", "password": "password" }

    Response → { "token": "eyJhbGci..." }

  2. Call Product API via Gateway

    GET https://localhost:5000/products Authorization: Bearer eyJhbGci...

    ✅ Response → [ { "Id": 1, "Name": "T-shirt", "Price": 499 }, ... ]

  3. Without Token → 401 Unauthorized.


🚀 Summary

  • AuthService issues JWT.

  • ProductService validates JWT.

  • ApiGateway (Ocelot) sits in front, validates tokens, and routes traffic.

🌐 API Gateway in Microservices

 🔑 What is API Gateway?

  • An API Gateway is a single entry point for all client requests in a microservices architecture.

  • Instead of the client calling each microservice directly, requests go through the Gateway which:

    • Routes the request to the right microservice.

    • Applies authentication, rate limiting, caching, logging, transformation, etc.

  • It’s like a traffic controller for microservices.

Popular API Gateways

  • Ocelot (for .NET Core)

  • Azure API Management (APIM)

  • Kong, NGINX, Zuul, AWS API Gateway, Istio


⚙️ How to Configure and Use API Gateway

Example: Ocelot in .NET Core

  1. Install Ocelot

dotnet add package Ocelot
  1. Configure Startup.cs

public void ConfigureServices(IServiceCollection services) { services.AddOcelot(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseOcelot().Wait(); }
  1. Add ocelot.json

{ "Routes": [ { "DownstreamPathTemplate": "/api/products", "UpstreamPathTemplate": "/products", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5001 } ] } ], "GlobalConfiguration": { "BaseUrl": "https://localhost:5000" } }

👉 Now, clients call https://localhost:5000/products and Ocelot forwards to http://localhost:5001/api/products.


🔒 How to Authenticate in API Gateway

Approaches:

  1. JWT Authentication

    • Client gets a JWT token from Identity Service.

    • API Gateway validates the token before forwarding.

    • Example Ocelot config:

    "AuthenticationOptions": { "AuthenticationProviderKey": "TestKey", "AllowedScopes": [] }
  2. API Keys

    • Clients pass an API Key in the header → Gateway validates.

  3. OAuth2 / OpenID Connect

    • API Gateway integrates with Identity Provider (Azure AD, Okta, IdentityServer).

  4. mTLS (Mutual TLS)

    • Client certificates are validated at the Gateway.


🛠 Responsibilities of API Gateway

  1. Routing → Forward request to correct microservice.

  2. Authentication & Authorization → Validate tokens/keys.

  3. Rate Limiting & Throttling → Protect services from overload.

  4. Load Balancing → Distribute traffic across instances.

  5. Caching → Improve performance by caching responses.

  6. Request/Response Transformation → Convert formats (e.g., XML ↔ JSON).

  7. Logging & Monitoring → Track requests, errors, performance.

  8. Security → Block malicious requests before reaching services.

  9. Versioning → Support multiple API versions (/v1/orders, /v2/orders).


🔥 Firewall in Microservices

What is Firewall in Microservices?

  • A firewall is a security layer that filters incoming/outgoing traffic based on rules.

  • In microservices, firewall ensures:

    • Only API Gateway can access microservices (direct external calls are blocked).

    • Only whitelisted IPs/ports are allowed.

    • Blocks malicious requests (SQL injection, DDoS, etc.).

Types of Firewalls

  1. Network Firewall → Controls traffic between external world and cluster (e.g., Azure NSG, AWS Security Groups).

  2. Application Firewall (WAF) → Protects against web attacks (SQL Injection, XSS).

  3. Service Mesh Security (Istio, Linkerd) → Provides fine-grained firewall-like policies inside the cluster.


✅ Summary

  • API Gateway = single entry point, routing + auth + monitoring + transformations.

  • Configuration = define routes, downstream services (ocelot.json, APIM policies, etc.).

  • Authentication = JWT, OAuth2, API Keys, mTLS.

  • Responsibilities = routing, security, rate limiting, logging, caching.

  • Firewall = network/application-level security that blocks unauthorized traffic before reaching microservices.

Blog Archive

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages