×

About the author

Sumit Kokal
Lead Engineer
Experienced Full Stack Engineer currently working as a Lead Engineer on the Gordian Project at Nitor, with expertise in building scalable and hi... Read More

Software Engineering   |      11 May 2026   |     20 min  |

A Practical Enterprise Guide to IAM, Token Exchange & Automated Onboarding

Highlights

Learn how to secure enterprise-grade .NET microservices using Keycloak with a practical, real-world approach to Identity and Access Management (IAM). This blog explores how organizations can implement centralized authentication, role-based access control, token exchange, and automated user onboarding for scalable distributed systems. It covers integrating Keycloak with .NET microservices, securing APIs with JWT tokens, enabling seamless service-to-service communication, and automating identity workflows to reduce manual effort. Designed for developers, architects, and IT leaders, the guide provides actionable insights, architecture best practices, and modern security strategies to build resilient, compliant, and cloud-ready enterprise applications.

2. New to This? Here Are 5 Key Terms

You will see these terms throughout the guide. Here is what each one means in plain English:

Term Meaning
OAuth2 An industry-standard protocol for authorization. It defines how an application can be granted permission to act on a user’s behalf without ever seeing the user’s password. Think of it as a secure “valet key” for APIs.
OpenID Connect A thin layer built on top of OAuth2 that adds user identity not just what the user can do, but who they are. Keycloak uses OpenID Connect to tell your app the user’s name, email, and roles inside the JWT token it issues.
SSO (Single Sign-On) A user logs in once through Keycloak and is automatically authenticated across all your connected applications. No repeated logins per service.
Realm A Keycloak workspace or tenant. It holds all your users, roles, and registered applications (clients) in one isolated space. Most teams create one realm per environment (e.g., a “dev” realm and a “prod” realm).
Client In Keycloak, a “client” is a registered application that is allowed to request tokens. Your .NET API, your frontend, and your mobile app are each a separate client in Keycloak.

3. Get Started Locally 3 Steps

You can have Keycloak running on your machine in under five minutes using Docker.

Step 1 – Run Keycloak with Docker

Open a terminal and run the following command. This starts Keycloak on port 8080 with a temporary admin account:

docker run -p 8080:8080 \

-e KC_BOOTSTRAP_ADMIN_USERNAME=admin \

-e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \

quay.io/keycloak/keycloak:latest start-dev

Step 2 – Create a Realm and Client

Once Keycloak is running, open http://localhost:8080 in your browser and log in with admin / admin. Then:

  1. Click Create Realm in the left sidebar. Give it a name e.g., enterprise.
  2. Inside your new realm, go to Clients → Create client. Name it enterprise-client. Set Client authentication to ON.
  3. Go to Realm roles and create at least one role, e.g., admin or user.
  4. Go to Users → Add user. Create a test user and assign the role from the Role mapping tab.

Step 3 – Connect Your .NET API

Install the required NuGet package and add two lines of middleware to Program.cs:

# Install the JWT Bearer package

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

// Program.cs — add these lines

builder.Services

.AddAuthentication("Bearer")

.AddJwtBearer(options =>

{

options.Authority = "http://localhost:8080/realms/enterprise";

options.Audience = "enterprise-client";

options.RequireHttpsMetadata = false; // false for local dev only

});

app.UseAuthentication();

app.UseAuthorization();

Abstract

Modern digital platforms demand secure, centralized identity management at scale. Keycloak an open-source Identity and Access Management (IAM) solution simplifies authentication and authorization for cloud-native .NET applications. In this guide, you will learn how to integrate Keycloak with .NET Core APIs, implement OAuth2 Token Exchange for secure microservice-to-microservice communication, automate user provisioning via the Keycloak Admin API, and design a scalable security architecture suitable for production enterprise use.

collateral

Download our exclusive Microservices Engineering Guide to discover proven strategies for building secure, scalable, and enterprise-ready .NET microservices with modern IAM and automation practices.

Why This Matters: The Enterprise IAM Challenge

Modern enterprise apps are built from many services, not one. That means many places where the wrong person could gain access and many places where a security gap can go unnoticed.

Without a solid identity strategy, you risk leaked credentials, unauthorized access, and failed audits. As teams and systems grow, managing who can do what becomes one of the hardest problems to get right.

Architecture Overview

The architecture below shows how authentication flows through the system. Each component plays a distinct role the Frontend handles user interaction, the .NET Identity Service orchestrates auth logic, Keycloak issues and validates tokens, and the Backend Microservices enforce access based on those tokens.

Authentication flow Through the system

Fig: Authentication flow Through the system

Component Roles

  • Frontend: Authenticates users and initiates the login flow.
  • .NET Identity Service: Orchestrates authentication, acts as token broker, and manages refresh tokens server-side.
  • Keycloak: Issues and validates JWTs, manages roles, users, and groups, and handles Token Exchange.
  • Backend Microservices: Receive audience-scoped, exchanged tokens; enforce authorization policy.

Implementation Steps

Step 1: Setting Up Keycloak

Deploy Keycloak (via Docker or a managed cloud offering) and configure a Realm for your enterprise. A Realm is an isolated namespace for users, roles, and clients.

Key configuration steps:

  • Create a Realm (e.g., enterprise)
  • Create a confidential Client for your .NET API (e.g., enterprise-client)
  • Enable Token Exchange on the client under Advanced Settings
  • Define Roles (e.g., admin, manager, user) at the Realm or Client level

Step 2: Configuring .NET JWT Authentication

In your .NET API, configure JWT Bearer authentication to validate tokens issued by Keycloak. The middleware automatically fetches Keycloak’s public keys from its JWKS endpoint to verify token signatures.

// Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;

using Microsoft.IdentityModel.Tokens;

builder.Services

.AddAuthentication(options =>

{

options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

})

.AddJwtBearer(options =>

{

options.Authority = "https://<KEYCLOAK-HOST>/realms/<REALM>";

options.Audience = "<CLIENT-ID>";

options.RequireHttpsMetadata = true;

options.TokenValidationParameters = new TokenValidationParameters

{

ValidateIssuer = true,

ValidateAudience = true,

ValidateLifetime = true,

ValidateIssuerSigningKey = true

};

});

var app = builder.Build();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();

Step 3: Enabling Authorization Roles and Policies

Once authentication is configured, protect individual endpoints using role-based or policy-based authorization. Keycloak embeds role claims directly inside the JWT, which .NET reads during request processing.

// Policy-based authorization

builder.Services.AddAuthorization(options =>

{

options.AddPolicy("AdminOnly", p => p.RequireClaim("role", "admin"));

options.AddPolicy("ManagerOnly", p => p.RequireClaim("role", "manager"));

});

// Protect a controller endpoint

[Authorize(Policy = "AdminOnly")]

[HttpGet("dashboard")]

public IActionResult GetAdminDashboard() => Ok("Welcome, Admin");

[Authorize(Policy = "ManagerOnly")]

[HttpGet("reports/confidential")]

public IActionResult GetConfidentialReport() => Ok("Manager-level report");

Step 4: Token Exchange for Microservice-to-Microservice Calls

Token Exchange is one of the most powerful and most overlooked features of Keycloak for enterprise architecture. Rather than forwarding the original user token to every internal service (which over-exposes credentials), the Identity Service requests a new, audience-scoped token from Keycloak for each downstream call.

Token Exchange Flow

Token Exchange Flow

Fig: Token Exchange Flow

The flow works as follows:

  1. The Frontend authenticates and receives an access token from the .NET Identity Service.
  2. When the Identity Service needs to call a downstream microservice, it sends the user’s token to Keycloak’s Token Endpoint using the OAuth2 Token Exchange grant type.
  3. Keycloak issues a new, audience-scoped token valid only for the intended microservice.
  4. The Identity Service uses this exchanged token to call the downstream API.
  5. Each microservice validates the token against Keycloak’s JWKS endpoint before processing the request.

Token Exchange .NET Implementation

public async Task<TokenExchangeResponse> ExchangeTokenAsync(

string subjectToken, string targetAudience)

{

var endpoint = $"realms/{_realm}/protocol/openid-connect/token";

var form = new FormUrlEncodedContent(new[]

{

new KeyValuePair<string,string>("grant_type",

"urn:ietf:params:oauth:grant-type:token-exchange"),

new KeyValuePair<string,string>("client_id", _clientId),

new KeyValuePair<string,string>("client_secret", _clientSecret),

new KeyValuePair<string,string>("subject_token", subjectToken),

new KeyValuePair<string,string>("requested_token_type",

"urn:ietf:params:oauth:token-type:access_token"),

new KeyValuePair<string,string>("audience", targetAudience)

});

var response = await _httpClient.PostAsync(endpoint, form);

response.EnsureSuccessStatusCode();

var content = await response.Content.ReadAsStringAsync();

return JsonSerializer.Deserialize<TokenExchangeResponse>(content)!;

}

Step 5: Token Refresh Handling Enterprise Pattern

In production enterprise systems, access tokens are intentionally short-lived (typically 5-15 minutes). The Identity Service must manage refresh tokens responsibly never exposing them to client applications.

Recommended Token Lifecycle Pattern

  • The Frontend receives only access tokens.
  • The Identity Service securely stores and rotates refresh tokens on server-side.
  • Tokens are proactively refreshed before expiry or on receiving a 401 response.
  • Exchanged service tokens remain short-lived and are not cached.

.NET Token Refresh Implementation

public async Task<TokenResponse> RefreshAccessTokenAsync(string refreshToken)

{

var endpoint = $"{_keycloakBaseUrl}/realms/{_realm}/protocol/openid-connect/token";

using var request = new HttpRequestMessage(HttpMethod.Post, endpoint);

request.Content = new FormUrlEncodedContent(new[]

{

new KeyValuePair<string,string>("grant_type", "refresh_token"),

new KeyValuePair<string,string>("client_id", _clientId),

new KeyValuePair<string,string>("client_secret", _clientSecret),

new KeyValuePair<string,string>("refresh_token", refreshToken)

});

var response = await _httpClient.SendAsync(request);

response.EnsureSuccessStatusCode();

var content = await response.Content.ReadAsStringAsync();

return JsonSerializer.Deserialize<TokenResponse>(content)!;

}

Keycloak Admin API Integration

Keycloak exposes a comprehensive REST Admin API that enables full programmatic control of users, groups, roles, and sessions. By integrating this API into your .NET service, you can completely automate the IAM side of user onboarding eliminating manual configuration and reducing operational overhead.

What the Admin API enables:

  • Create, update, and deactivate users
  • Create and manage group hierarchies
  • Assign realm-level and client-level roles
  • Map users to groups (inheriting group roles automatically)
  • Fetch group hierarchies and role assignments

Approach: Client Credentials Flow

Create a dedicated confidential client in Keycloak with admin privileges. Your .NET service uses the Client Credentials grant to obtain an admin access token, then calls Admin REST endpoints with that token.

Automated User & Group Onboarding

With the Admin API integrated, onboarding an entire organization becomes a fully automated workflow triggered from your application

Onboarding Flow

  1. An administrator creates a new organization in the application.
  2. The .NET service calls the Admin API to create a corresponding Keycloak group.
  3. Predefined roles are assigned to the group via the Admin API.
  4. When a new user is added to the organization, the service creates the user via Admin API.
  5. The user is mapped to the organization group – group roles apply automatically.

Advanced Topics

Multi-Tenancy

For SaaS platforms serving multiple customers, Keycloak supports two multi-tenancy models: separate Realms per tenant (strongest isolation) or a single Realm with groups and custom claims to partition tenants. The Realm-per-tenant model simplifies auditing and data residency compliance but increases operational overhead.

Observability & Audit Logging

Keycloak emits detailed audit events for every authentication, token issuance, and admin action. Pipe these to your Security Information and Event Management (SIEM) and set alerts for failed logins above threshold, token exchange from unexpected clients, role assignment changes outside of onboarding windows, and admin API calls outside business hours.

Conclusion

Integrating Keycloak with a .NET Identity Service gives enterprise teams a robust, standards-compliant Identity and Access Management (IAM) backbone without building authentication infrastructure from scratch. By combining OAuth2 Token Exchange for secure service delegation, Keycloak Admin API for automated provisioning, and .NET’s JWT middleware for enforcement, you achieve an architecture that is secure, scalable, and auditable.

References & Resources

Looking to implement secure, scalable identity solutions?

Connect with Nitor Infotech to build robust Keycloak-based IAM and secure your microservices architecture.

subscribe image

Subscribe to our
fortnightly newsletter!

we'll keep you in the loop with everything that's trending in the tech world.

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.