Menu

Showing posts with label API Authentication. Show all posts
Showing posts with label API Authentication. Show all posts

15 Jun 2026

πŸ›‘️ API Authentication & API Gateway Security Explained - Part 6

API Authentication & API Gateway Security Explained
  • Welcome to Part 6 of the Authentication & Identity Security series.
  • This article explains how APIs are authenticated and protected in enterprise environments.
  • Designed for Middleware, DevOps, Cloud, API, and Application Support Engineers.
  • Includes examples using API Keys, Basic Authentication, JWT, OAuth2, API Gateway, Azure API Management, NGINX, and backend services.


Introduction

In Part 5, we compared JWT, Sessions, and Cookies. Now we will move one level deeper into API security.

Modern applications commonly expose REST APIs for mobile apps, web apps, partner integrations, microservices, automation tools, and cloud platforms. These APIs must be protected so that only trusted users, systems, or applications can access them.

Key Concept:
API Authentication verifies who is calling the API before allowing access to backend services.

What is API Authentication?

API Authentication is the process of verifying the identity of a client application, user, service account, or system before allowing it to call an API.

API consumers may include:

  • Web applications
  • Mobile applications
  • Partner systems
  • Microservices
  • Automation scripts
  • CI/CD tools
  • Monitoring tools

Simple API Flow

Client Application
        │
        ▼
Authentication Credential
        │
        ▼
API Gateway / API Server
        │
        ▼
Credential Validation
        │
        ▼
Backend Service Access

Why API Authentication is Important

APIs expose business data and backend functions. Without proper authentication, attackers or unauthorized systems may call sensitive APIs.

  • Protects customer and business data
  • Prevents unauthorized API access
  • Supports audit and compliance requirements
  • Protects backend services from misuse
  • Enables secure partner and system integration
  • Supports identity-based access control
Enterprise View:
In production environments, APIs are usually protected using a combination of authentication, authorization, rate limiting, logging, WAF, and API Gateway policies.

Common API Authentication Methods

Method Common Usage Security Level
API Key Simple application identification Basic
Basic Authentication Legacy/internal APIs Low to Medium
JWT Bearer Token Modern APIs and microservices High
OAuth2 Enterprise delegated access High
mTLS System-to-system authentication Very High

API Key Authentication

API Key authentication uses a unique key to identify the application or client calling the API.

Example

GET /api/customer HTTP/1.1
Host: api.company.com
x-api-key: 9f8a7b6c5d4e

The API Gateway or backend API validates the key before processing the request.

Advantages

  • Simple to implement
  • Useful for internal or low-risk APIs
  • Good for identifying applications

Limitations

  • Does not identify the actual user
  • Can be leaked if stored insecurely
  • Should not be used alone for sensitive APIs

Basic Authentication

Basic Authentication sends username and password encoded in the Authorization header.

Example

Authorization: Basic base64(username:password)

Although the value is encoded, it is not encrypted. Therefore, Basic Authentication must always be used only over HTTPS.

Security Note:
Basic Authentication is simple but not recommended for modern public APIs unless combined with HTTPS, strong password policy, and additional controls.

JWT Bearer Token Authentication

JWT Bearer Token authentication is commonly used in modern APIs.

After successful login, the client receives a JWT access token and sends it with every API request.

Example API Request

GET /api/policies HTTP/1.1
Host: api.company.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Validation Performed by API

  • Validate token signature
  • Check token expiry
  • Validate issuer
  • Validate audience
  • Check user roles or claims
Middleware View:
JWT validation can be performed at API Gateway, reverse proxy, application middleware, or backend service level.

OAuth2 API Authentication

OAuth2 is commonly used when an application needs delegated access to protected APIs.

Instead of sharing user passwords with APIs, the application receives an access token from an authorization server.

OAuth2 API Flow

Client Application
        │
        ▼
Authorization Server
        │
        ▼
Access Token Issued
        │
        ▼
API Request With Bearer Token
        │
        ▼
Protected API

Common OAuth2 Components

  • Client: Application requesting access
  • Resource Owner: User or account owner
  • Authorization Server: Issues tokens
  • Resource Server: API being accessed

OAuth2 is commonly used with Azure Entra ID, identity providers, API Gateways, and enterprise SSO platforms.


OAuth2 vs JWT

Many engineers confuse OAuth2 and JWT and assume they are the same thing. They are related but serve different purposes.

Simple Rule:
OAuth2 is the process used to obtain access tokens.
JWT is a token format commonly used for those access tokens.

Airport Analogy

  • OAuth2 = Security verification process
  • JWT = Boarding pass issued after verification

OAuth2 Flow

User
  │
  ▼
Application
  │
  ▼
Authorization Server
  │
  ▼
User Login & Consent
  │
  ▼
Access Token Issued

JWT Example

Header.Payload.Signature

JWT defines the structure of the token. OAuth2 defines how the token is obtained.

Azure Example

User
 │
 ▼
Microsoft Entra ID
 │
OAuth2 Authorization Flow
 │
 ▼
JWT Access Token
 │
 ▼
Azure API Management
 │
 ▼
Backend API
OAuth2JWT
Authorization FrameworkToken Format
Defines how tokens are obtainedDefines token structure
Handles login and consent flowContains claims and signature
Can issue JWT or opaque tokensDoes not define login process
Used by Entra ID, Okta, KeycloakCommon access token format
Interview Answer:
OAuth2 is an authorization framework that defines how applications obtain access tokens. JWT is a token format commonly used to represent those access tokens.

What is an API Gateway?

An API Gateway is a centralized entry point for APIs. It sits between clients and backend services.

Client
  │
  ▼
API Gateway
  │
  ▼
Backend API / Microservice

Instead of exposing backend services directly, organizations expose APIs through an API Gateway.

Common API Gateway Products

  • Azure API Management
  • AWS API Gateway
  • Apigee
  • Kong Gateway
  • NGINX
  • IBM API Connect

API Gateway Security Controls

API Gateways provide multiple security and governance controls.

  • API authentication
  • JWT validation
  • OAuth2 integration
  • API key validation
  • Rate limiting
  • IP whitelisting
  • Request validation
  • Header validation
  • WAF integration
  • Logging and monitoring
  • Backend routing
  • Throttling and quota management
Production Tip:
Do not expose backend APIs directly to the internet. Use API Gateway, WAF, authentication policies, logging, and rate limiting.

Enterprise Architecture Example

Mobile App / Web App / Partner System
              │
              ▼
        WAF / CDN Layer
              │
              ▼
        API Gateway
              │
     ┌────────┼────────┐
     │        │        │
 JWT Validation   Rate Limit   Logging
     │        │        │
     └────────┼────────┘
              │
              ▼
       Backend API Service
              │
              ▼
       Database / Core System

In this model, API Gateway validates the caller before forwarding traffic to backend services.

Benefits

  • Centralized security enforcement
  • Reduced backend exposure
  • Improved monitoring and auditability
  • Better control over partner integrations
  • Reusable authentication and authorization policies

Azure API Management Example

Azure API Management can secure APIs using subscription keys, JWT validation, OAuth2 integration, and backend policies.

Typical Flow

Client Application
        │
        ▼
Azure API Management
        │
        ▼
Validate JWT / API Key
        │
        ▼
Azure App Service / AKS / VM API

Common Azure API Management Controls

  • Subscription key validation
  • JWT validation policy
  • OAuth2 / OpenID Connect integration
  • IP filtering
  • Rate limiting
  • Request and response transformation
  • Backend routing

JWT Header Example

Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

NGINX / Reverse Proxy Example

NGINX can be used as a reverse proxy in front of backend APIs. It can enforce TLS, route traffic, validate headers, limit requests, and integrate with authentication services.

Client
  │
  ▼
NGINX Reverse Proxy
  │
  ▼
Tomcat / JBoss / Spring Boot API

Common NGINX API Security Use Cases

  • HTTPS termination
  • Header forwarding
  • Rate limiting
  • IP allowlist / denylist
  • Reverse proxy routing
  • Basic authentication for internal APIs

Authentication Method Comparison

Method Best For Strength Limitation
API Key Application identification Simple and fast Does not identify user
Basic Auth Legacy/internal APIs Easy to implement Password exposure risk if misused
JWT Modern APIs Stateless and scalable Token theft and expiry handling
OAuth2 Delegated access Enterprise-grade authorization More complex setup
mTLS System-to-system APIs Strong certificate-based trust Certificate lifecycle management

Common API Authentication Issues

Issue Possible Cause
401 Unauthorized Missing, expired, or invalid token
403 Forbidden User authenticated but not authorized
Invalid API key Wrong key or inactive subscription
Invalid JWT signature Wrong signing key or modified token
Audience validation failed Token issued for different API
Rate limit exceeded Too many requests from client
CORS issue Browser blocked cross-origin API request

Best Practices

  • Always use HTTPS for API communication.
  • Do not expose backend APIs directly to the internet.
  • Use API Gateway for centralized authentication and policy enforcement.
  • Use JWT or OAuth2 for modern APIs.
  • Keep access tokens short-lived.
  • Validate issuer, audience, expiry, and signature.
  • Use API keys only for application identification or low-risk APIs.
  • Apply rate limiting and throttling.
  • Log API access for audit and troubleshooting.
  • Use WAF for internet-facing APIs.
  • Rotate secrets, API keys, and certificates regularly.

Key Takeaways

  • API Authentication verifies who is calling the API.
  • API Keys are simple but not enough for sensitive APIs.
  • Basic Authentication should be avoided for modern public APIs unless strongly protected.
  • JWT Bearer Tokens are widely used for modern API authentication.
  • OAuth2 is used for delegated access and enterprise integrations.
  • API Gateways centralize authentication, routing, monitoring, and security policies.
  • Azure API Management, NGINX, Apigee, Kong, and IBM API Connect are common gateway solutions.

What’s Next?

Next Article:
Part 7 – OAuth2, OpenID Connect (OIDC) & SAML Explained

In the next article, we will understand OAuth2, OIDC, and SAML, and how these protocols are used in enterprise SSO, API access, and identity federation.


Series: Authentication & Identity Security for Middleware, DevOps & Cloud Engineers
Author: Pradeep V
Blog: MiddlewareBox.com


🎫 JWT & Token-Based Authentication Explained - Part 4

JWT & Token-Based Authentication Explained
  • Welcome to Part 4 of the Authentication & Identity Security series.
  • This article explains JWT, access tokens, refresh tokens, and bearer tokens.
  • Designed for Middleware, DevOps, Cloud, API, and Application Support Engineers.
  • Includes enterprise examples using APIs, Docker, Azure Entra ID, API Gateway, and modern authentication flows.


Introduction

In Part 3, we learned the difference between stateful and stateless applications. Traditional enterprise applications commonly use sessions and JSESSIONID, while modern applications and APIs commonly use tokens.

One of the most popular token formats used in modern authentication is JWT.

JWT Full Form:
JWT stands for JSON Web Token.

What is JWT?

JWT, or JSON Web Token, is a compact and signed token format used to securely exchange information between a client and a server.

A JWT can carry identity and authorization information such as:

  • User ID
  • Email address
  • User role
  • Issuer
  • Audience
  • Token expiry time

JWT is commonly used in APIs, microservices, cloud applications, mobile applications, and Single Sign-On systems.


Why JWT is Used

JWT is widely used because it supports stateless authentication. The application does not need to store the user session in server memory.

  • Useful for REST APIs
  • Works well with Docker-based applications
  • Supports microservices architecture
  • Easy to validate at API Gateway level
  • Used by OAuth2 and OpenID Connect flows
  • Used by identity providers such as Azure Entra ID
Cloud View:
JWT helps applications scale horizontally because any backend server can validate the token without depending on server-side session memory.

JWT Structure

A JWT contains three parts separated by dots.

Header.Payload.Signature

Example JWT format:

xxxxx.yyyyy.zzzzz

1. Header

The header contains token type and signing algorithm.

{
  "alg": "HS256",
  "typ": "JWT"
}

2. Payload

The payload contains claims. Claims are information about the user or token.

{
  "sub": "pradeep",
  "role": "admin",
  "iss": "https://login.company.com",
  "aud": "api.company.com",
  "exp": 1789459200
}

Common JWT Claims

Claim Meaning
subSubject or User ID
issIssuer of the token
audAudience or target application
expToken expiry time
iatIssued at time
roleUser role or permission

3. Signature

The signature is used to verify that the token has not been modified.

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)
Important:
JWT payload is encoded, not encrypted by default. Do not store passwords, secrets, or sensitive personal data inside JWT payload.

How JWT Works

User
 │
 ▼
Login Request
 │
 ▼
Authentication Server
 │
 ▼
Credentials Validated
 │
 ▼
JWT Generated
 │
 ▼
JWT Returned To Client
 │
 ▼
Client Sends JWT With API Requests
 │
 ▼
API Validates JWT
 │
 ▼
Access Granted

Step 1: User Login

POST /login
username=pradeep
password=********

Step 2: JWT Returned

{
  "access_token": "eyJhbGciOiJIUzI1NiIs..."
}

Step 3: API Request With JWT

GET /api/customer
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

The API validates the token signature, expiry, issuer, audience, and claims before allowing access.


Is JWT Generated Every Time?

No. JWT is not generated for every API request.

A JWT is usually generated once during successful login or authentication. The same token is reused for multiple API requests until it expires.

Login
 │
JWT Generated Once
 │
Same JWT Sent With Every API Request
 │
Token Expires
 │
New Token Required

When is a New JWT Generated?

  • When the user logs in again
  • When the access token expires and a refresh token is used
  • When the authentication server rotates or renews tokens
  • When the user signs out and signs in again
Important:
The client sends the same JWT with every request using the Authorization header until the token expires.

Access Token, Refresh Token & Bearer Token

Token Type Purpose Typical Lifetime
Access Token Used to access APIs and protected resources Short-lived
Refresh Token Used to get a new access token Longer-lived
Bearer Token Token sent in Authorization header Depends on token expiry

Bearer Token Example

Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Bearer means whoever has the token can use it. That is why token storage and transport security are very important.


Enterprise Middleware Example

Traditional Session-Based Application

Browser
   │
JSESSIONID Cookie
   │
IBM HTTP Server
   │
WebSphere / JBoss / Tomcat
   │
Session Stored in JVM Memory

This is commonly used in traditional enterprise web applications.

Modern JWT-Based API

Client Application
   │
Authorization: Bearer JWT
   │
API Gateway
   │
Backend API / Microservice
   │
Token Validated

This is commonly used in APIs, microservices, Docker deployments, and cloud-native applications.


Azure Entra ID Example

Azure Entra ID can act as an identity provider and issue tokens after successful authentication.

User
 │
 ▼
Application
 │
 ▼
Azure Entra ID Login
 │
 ▼
MFA / Conditional Access
 │
 ▼
Access Token Issued
 │
 ▼
Application Calls API

The API validates the token issued by Azure Entra ID before allowing access to protected resources.

Enterprise Use Case:
Azure Entra ID tokens are commonly used for Microsoft 365, Azure Portal, enterprise applications, APIs, and Single Sign-On integrations.

JWT Security Best Practices

  • Always use HTTPS to protect tokens in transit.
  • Keep access tokens short-lived.
  • Use refresh tokens carefully and store them securely.
  • Validate token signature on every request.
  • Validate issuer and audience claims.
  • Never store passwords or secrets inside JWT payload.
  • Use secure storage for tokens in browser or mobile applications.
  • Rotate signing keys periodically.
  • Use API Gateway or identity middleware for centralized validation.

Session vs JWT

Point Session JWT
ArchitectureStatefulStateless
User DataStored on serverStored as token claims
IdentifierJSESSIONIDBearer Token
ScalingNeeds sticky session or replicationEasier horizontal scaling
Common UseTraditional web appsAPIs and microservices
Example PlatformWebSphere, JBoss, TomcatAPI Gateway, Docker, Cloud APIs

Common JWT Issues

Issue Possible Cause
401 UnauthorizedToken expired or invalid
Invalid signatureWrong signing key or modified token
Audience validation failedToken issued for different API
Issuer validation failedWrong identity provider configured
Token too largeToo many claims added
Token theft riskInsecure storage or missing HTTPS

Key Takeaways

  • JWT stands for JSON Web Token.
  • JWT contains Header, Payload, and Signature.
  • JWT is commonly used for stateless authentication.
  • A JWT is usually generated during login and reused until expiry.
  • Access tokens are used to access APIs.
  • Refresh tokens are used to get new access tokens.
  • Bearer tokens are sent in the Authorization header.
  • JWT is widely used in APIs, Docker applications, cloud platforms, and microservices.

What’s Next?

Next Article:
Part 5 – JWT vs Session vs Cookies

In the next article, we will compare JWT, sessions, and cookies in detail and understand when to use each approach in enterprise applications.


Series: Authentication & Identity Security for Middleware, DevOps & Cloud Engineers
Author: Pradeep V
Blog: MiddlewareBox.com