Showing posts with label AuthService → issues JWT tokens. Show all posts
Showing posts with label AuthService → issues JWT tokens. Show all posts

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.

Blog Archive

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages