Tuesday, October 7, 2025

🔑 Where to Configure Ports in .NET Core

 There are 3 main ways:


1️⃣ launchSettings.json (Local Development Only)

  • Located in:
    Properties/launchSettings.json

Example:

{ "profiles": { "ProductService": { "commandName": "Project", "dotnetRunMessages": true, "applicationUrl": "http://localhost:5002;https://localhost:7002", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }

👉 This means:

  • ProductService will listen on http://localhost:5002 and https://localhost:7002.

  • Useful for local debugging.


2️⃣ appsettings.json or appsettings.{Environment}.json

  • You can configure Kestrel endpoints directly.

Example:

{ "Kestrel": { "Endpoints": { "Http": { "Url": "http://localhost:5002" }, "Https": { "Url": "https://localhost:7002" } } } }

👉 This works in development, staging, and production.
👉 More flexible, especially when deploying in Docker/Kubernetes.


3️⃣ Hardcode in Program.cs (Not Recommended for Production)

var builder = WebApplication.CreateBuilder(args); builder.WebHost.UseUrls("http://localhost:5002", "https://localhost:7002"); var app = builder.Build(); app.MapControllers(); app.Run();

👉 Quick way to bind to specific ports, but harder to manage in large deployments.


⚙️ Best Practices

  1. Local Development → use launchSettings.json.

  2. Production (IIS, Azure, Docker, Kubernetes)

    • Use appsettings.json (Kestrel:Endpoints).

    • Or environment variables → DOTNET_URLS=http://+:5002.

  3. Dockerized Microservices → expose ports in Dockerfile / docker-compose.yml. Example:

    EXPOSE 5002
    ports: - "5002:5002"

✅ Summary

  • launchSettings.json → local dev only.

  • appsettings.json (Kestrel) → preferred for production.

  • Program.cs → UseUrls() → quick overrides.

  • Environment Variables / Docker → best in containerized/cloud setups.

🔑 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