← Back to Article List         
Auth: API Gateway vs Microservice

Auth: API Gateway vs Microservice

Published on 28 Sep 2026     11 min read Microservices
API Gateway

Authentication & Authorization: API Gateway or Microservice?

In a Microservices architecture, authentication and authorization are related but should not necessarily be handled at exactly the same layer.

A strong general design is:

Authentication can be centralized at the API Gateway, while each Microservice should still enforce the authorization rules for the resources and business operations it owns.

In security-sensitive systems, Microservices should also validate the security context/token rather than blindly trusting that “the gateway already checked it.”


1. First: Authentication vs Authorization

These two concepts are different.

Authentication — “Who are you?”

Authentication verifies the caller's identity.

For example:

Username + Password
        ↓
Identity Provider
        ↓
JWT Access Token
        ↓
Authenticated User

Example JWT claims:

{
  "sub": "1001",
  "name": "Syed",
  "role": "Admin"
}

Authentication answers:

Is this caller genuinely Syed/User 1001?

Authorization — “What are you allowed to do?”

Authorization happens after authentication.

For example:

User = Syed
Role = Admin

Can access:
✓ GET /orders
✓ POST /orders
✓ DELETE /orders/10

Another user:

Role = Customer

✓ GET /orders/10
✗ DELETE /orders/10

So:

Authentication
      ↓
Who are you?
      ↓
Authorization
      ↓
What can you do?

2. Where Should Authentication Happen?

A common architecture is:

Client
   │
   │ JWT
   ▼
API Gateway
   │
   │ Authentication
   ▼
Microservice

The API Gateway is a useful centralized enforcement point for authentication.

For example:

Client
   │
   │ Bearer JWT
   ▼
┌────────────────────────┐
│      API Gateway       │
│                        │
│ Validate JWT           │
│ Validate signature     │
│ Validate issuer        │
│ Validate audience      │
│ Validate expiration    │
└────────────┬───────────┘
             │
             ▼
       Microservice

Invalid requests can be rejected before they reach internal services.


Why Authenticate at the Gateway?

Suppose you have:

Product Service
Order Service
Payment Service
Customer Service
Shipping Service

Without gateway-level authentication:

                ┌── Product → Authenticate
                ├── Order   → Authenticate
Client ─────────┼── Payment → Authenticate
                ├── Customer→ Authenticate
                └── Shipping→ Authenticate

With a gateway:

Client
   │
   ▼
API Gateway
   │
   │ Authentication
   ▼
Authenticated request
   │
   ├── Product
   ├── Order
   ├── Payment
   └── Customer

This gives you a centralized first security boundary.


3. Should Microservices Also Validate the Token?

Generally, yes for protected services.

Do not design your entire security model around:

“If the request reached the Microservice, it must already be trusted.”

A stronger model is:

Client
   │
   │ JWT
   ▼
API Gateway
   │
   │ Validate JWT
   ▼
Microservice
   │
   │ Validate JWT / trusted identity context
   │
   │ Apply authorization
   ▼
Business Logic

This is commonly described as defense in depth.

It becomes particularly important if services can potentially be reached through:

  • internal networks,
  • another Microservice,
  • administrative systems,
  • background workers,
  • misconfigured infrastructure,
  • alternate ingress paths.

4. Where Should Authorization Happen?

This requires more nuance.

Some coarse-grained authorization can happen at the gateway.

For example:

/admin/*

Required Role:
Admin

The gateway could reject:

Customer → /admin/users
              ↓
            403

But business/domain authorization should normally be enforced by the Microservice that owns the resource.


Why?

Consider:

DELETE /api/orders/1001

Suppose the authenticated token contains:

{
  "sub": "500",
  "role": "Customer"
}

The important question isn't merely:

Can a Customer call the Order API?

The real business question may be:

Does Customer 500 own Order 1001, and is that order currently in a state that allows cancellation?

The gateway generally doesn't own that business data.

The Order Service does.

API Gateway

"Is this authenticated caller allowed
to access this broad route?"

              ↓

Order Service

"Does this caller own Order 1001?"

"Is Order 1001 cancellable?"

"Does this operation satisfy our
business authorization rules?"

That is a crucial distinction.


Recommended Architecture

A practical architecture looks like this:

Client
   │
   │ JWT
   ▼
┌─────────────────────────┐
│      API Gateway        │
│                         │
│ Authentication          │
│ Token validation        │
│ Coarse authorization    │
│ Rate limiting           │
│ Routing                 │
└────────────┬────────────┘
             │
             │ JWT / trusted identity
             ▼
┌─────────────────────────┐
│     Order Service       │
│                         │
│ Token validation        │
│ Authorization           │
│ Business authorization  │
│ Resource ownership      │
└────────────┬────────────┘
             │
             ▼
          Database

So the responsibility can be summarized as:

Responsibility Gateway Microservice
Initial JWT validation ✓ Can/should validate for protected boundaries
Reject invalid token early ✓ ✓ if independently reachable
Coarse route authorization ✓ Optional/redundant enforcement
Role/policy authorization Possible ✓
Resource ownership ✗ ✓
Domain/business authorization ✗ ✓
Rate limiting ✓ Sometimes
Routing ✓ ✗

5. Example Using JWT

Assume the user logs in through an Identity/Auth Service:

Client
   │
   │ Login
   ▼
Identity Service
   │
   │ Generate JWT
   ▼
Client

The client receives:

eyJhbGciOiJIUzI1NiIs...

Then:

Client
   │
   │ Authorization:
   │ Bearer <token>
   ▼
API Gateway
   │
   ▼
Order Service

Authentication at API Gateway

For example, in a YARP-based gateway:

using Microsoft.AspNetCore.Authentication.JwtBearer;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://identity.company.com";
        options.Audience = "api";
    });

builder.Services.AddAuthorization();

builder.Services
    .AddReverseProxy()
    .LoadFromConfig(
        builder.Configuration.GetSection("ReverseProxy"));

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapReverseProxy();

app.Run();

The important pipeline is:

Request
   ↓
UseAuthentication()
   ↓
UseAuthorization()
   ↓
YARP
   ↓
Microservice

Protecting a YARP Route

You can associate an authorization policy with a proxy route.

Conceptually:

{
  "ReverseProxy": {
    "Routes": {
      "order-route": {
        "ClusterId": "order-cluster",

        "AuthorizationPolicy": "authenticated",

        "Match": {
          "Path": "/orders/{**catch-all}"
        }
      }
    }
  }
}

Then define the policy:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("authenticated", policy =>
    {
        policy.RequireAuthenticatedUser();
    });
});

Now:

No JWT
  ↓
Gateway
  ↓
401 Unauthorized

Valid JWT
  ↓
Gateway
  ↓
Order Service

6. Authorization Inside the Microservice

Suppose the Order Service has:

[Authorize]
[HttpDelete("{orderId}")]
public async Task<IActionResult> CancelOrder(int orderId)
{
    // Business authorization
}

But [Authorize] alone doesn't answer whether the current user owns the order.

You may need:

[Authorize]
[HttpDelete("{orderId}")]
public async Task<IActionResult> CancelOrder(int orderId)
{
    var userId = User.FindFirst("sub")?.Value;

    var order = await _orderService.GetByIdAsync(orderId);

    if (order == null)
        return NotFound();

    if (order.CustomerId != userId)
        return Forbid();

    await _orderService.CancelAsync(orderId);

    return NoContent();
}

Now the Microservice makes the business authorization decision:

User ID = 500

DELETE /orders/1001

        ↓

Order Service

        ↓

Order.CustomerId == 500?

        ├── NO  → 403 Forbidden
        │
        └── YES
              ↓
         Cancel Order

The gateway cannot reliably perform this check because the Order Service owns the order information.


7. Role-Based Authorization

Suppose only administrators can delete products.

Gateway could perform a broad check:

DELETE /products/*
        ↓
Requires Admin

But the Product Service should still protect its sensitive endpoint when appropriate:

[Authorize(Roles = "Admin")]
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
    // delete product
}

This is particularly useful when the service has other trusted callers besides the public gateway.


8. Policy-Based Authorization

For more complex authorization, ASP.NET Core policies are preferable to scattering role checks throughout controllers.

For example:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("CanCancelOrder", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("permission", "orders.cancel");
    });
});

Then:

[Authorize(Policy = "CanCancelOrder")]
[HttpDelete("{id}")]
public IActionResult CancelOrder(int id)
{
    ...
}

The JWT might contain:

{
  "sub": "500",
  "permission": [
    "orders.read",
    "orders.cancel"
  ]
}

9. What About Service-to-Service Calls?

This is another reason authentication should not exist only at the external gateway.

Imagine:

Client
   ↓
Gateway
   ↓
Order Service
   ↓
Payment Service

The Payment Service receives a request from the Order Service, not directly from the gateway.

Therefore, internal service-to-service security must also be designed.

For example:

Order Service
      │
      │ Service credential/token
      ▼
Payment Service
      │
      │ Authenticate Order Service
      │ Authorize operation
      ▼
Process Payment

You may use approaches such as:

  • OAuth 2.0 access tokens
  • Client Credentials flow
  • workload identity
  • mTLS
  • platform/service-mesh identity

depending on the infrastructure.


10. Important: Don't Simply Trust Custom Headers

A dangerous design is:

Gateway validates JWT

Gateway adds:

X-User-Id: 500
X-Role: Admin

and the Microservice blindly trusts:

X-Role: Admin

If an attacker can bypass the gateway:

Attacker
   │
   │ X-Role: Admin
   ▼
Microservice

you have a serious vulnerability.

If identity is propagated through headers, the architecture must ensure those headers can only come from a trusted authenticated intermediary, and client-supplied versions are stripped/replaced.

Passing and independently validating a signed access token is often easier to reason about.


11. 401 vs 403

This is a very common interview question.

401 Unauthorized

Despite the name, 401 normally means:

Authentication is missing or invalid.

Example:

No JWT
Expired JWT
Invalid JWT signature

       ↓

401 Unauthorized

403 Forbidden

Means:

The caller is authenticated, but does not have permission.

Example:

JWT valid
User authenticated

Role = Customer

DELETE /admin/users/10

       ↓

403 Forbidden

Remember:

401
 ↓
Who are you?
Authentication problem


403
 ↓
I know who you are,
but you cannot do this.
Authorization problem

Advantages of Gateway Authentication

1. Centralized authentication

Invalid external requests can be rejected before reaching Microservices.

2. Reduced unnecessary traffic

Bad tokens don't have to travel through the internal system.

3. Consistent external security policy

Common gateway-facing security requirements can be applied centrally.

4. Protects downstream resources

Unauthorized traffic can be stopped earlier.

5. Simplifies public ingress

Clients interact with a consistent security boundary.


Disadvantages of Gateway-Only Security

If you rely only on the gateway:

Client
   ↓
Gateway ← Security exists only here
   ↓
Microservices ← Trust everything

you create an implicit trust assumption.

Problems can arise if:

  • Gateway is bypassed
  • Network configuration is incorrect
  • Another internal service calls the Microservice
  • A new ingress path is introduced
  • Internal credentials are compromised

Therefore:

“Internal network” should not automatically mean “trusted request.”


Recommended Pattern

For a typical protected Microservices system:

                 Identity Provider
                        │
                        │ JWT
                        ▼
Client ─────────► API Gateway
                        │
                        │ ① Authenticate
                        │ ② Coarse authorization
                        │ ③ Rate limit
                        │
                        ▼
                  Microservice
                        │
                        │ ④ Validate identity
                        │ ⑤ Authorization
                        │ ⑥ Resource ownership
                        │ ⑦ Business rules
                        ▼
                     Database

This gives you:

Gateway
   ↓
Edge security / coarse policies

+

Microservice
   ↓
Service and business security

Advantages of This Approach

  • Defense in depth
  • Centralized external authentication
  • Business rules stay with the service that owns them
  • Better protection against gateway bypass
  • Supports service-to-service security
  • Each service remains responsible for protecting its own resources

Disadvantages

1. Some duplicated validation

The gateway and Microservice may both validate tokens.

2. More configuration

Authentication/authorization configuration may exist across multiple services.

3. More complex identity propagation

You need a clear strategy for forwarding user/service identity.

4. Key and policy management

Multiple services must be configured consistently with trusted issuers, audiences, keys, claims, etc.

These are usually acceptable costs for stronger isolation in security-sensitive Microservices architectures.


Key Points

For interview preparation, remember:

  • Authentication = Who are you?
  • Authorization = What are you allowed to do?
  • API Gateway is a good place for centralized external authentication.
  • Gateway can perform coarse-grained authorization.
  • Microservices should enforce service/resource/business authorization.
  • Protected Microservices should not blindly assume every request reaching them is trusted.
  • Service-to-service calls also require authentication/authorization.
  • 401 generally means missing/invalid authentication.
  • 403 means authenticated but insufficient permission.
  • Avoid blindly trusting client-controllable identity headers.
  • Keep domain-specific authorization close to the Microservice that owns the domain data.

Interview Questions & Answers

Q1. Where should authentication happen in Microservices?

Answer:

Authentication is commonly performed at the API Gateway for external requests so invalid tokens can be rejected early. Protected Microservices may also validate the access token or trusted identity context as part of defense in depth.


Q2. Where should authorization happen?

Answer:

Coarse-grained authorization can be performed at the gateway, but business and resource-level authorization should normally be enforced inside the Microservice that owns the resource.


Q3. Why not put all authorization in the API Gateway?

Because the gateway usually does not own domain data.

For example:

Can User 500 cancel Order 1001?

The Order Service knows:

Who owns Order 1001?
What state is it in?
Is cancellation permitted?

Therefore the Order Service should make that business authorization decision.


Q4. Should the Microservice validate JWT if the gateway already validates it?

For protected services, this is often appropriate, especially when services have multiple possible callers or can be reached through paths other than the public gateway.

It provides defense in depth rather than blindly trusting the network location.


Q5. What is the difference between 401 and 403?

401 means authentication is missing or invalid.

403 means the user is authenticated but does not have permission to perform the operation.


Q6. Should internal Microservices trust each other automatically?

Generally, no. Service-to-service communication should have an explicit trust model, often using service credentials/tokens, workload identity, or mTLS.


Q7. Can the API Gateway handle role-based authorization?

Yes. A gateway can apply coarse role/policy restrictions to routes. However, sensitive operations should still be protected at the owning Microservice where appropriate.


Interview-ready answer

In a Microservices architecture, authentication is commonly centralized at the API Gateway so invalid external requests can be rejected early. The gateway can also perform coarse-grained authorization. However, each Microservice should enforce the authorization rules for the resources and business operations it owns, such as checking whether a user owns an order or has permission to cancel it. Protected services should not blindly trust that a request is safe simply because it passed through the gateway. This provides defense in depth and also supports secure service-to-service communication.