AKS Pod Connecting to PostgreSQL Database using Workload Identity - Passwordless Authentication
Introduction
Securely connecting Kubernetes pods to Azure services like PostgreSQL is essential for modern cloud applications. Traditional approaches using connection strings with usernames and passwords pose security risks and management overhead. Azure Kubernetes Service (AKS) workload identity provides a secure, passwordless authentication mechanism that enables pods to authenticate to Azure services using Microsoft Entra ID (formerly Azure Active Directory) identities.
This article demonstrates how to configure AKS workload identity to enable pods to connect to Azure Database for PostgreSQL Flexible Server using managed identities, eliminating the need for storing database credentials in the application code or Kubernetes secrets.
Key Concepts
Before diving into the implementation details, it's essential to understand the fundamental concepts that enable passwordless authentication between AKS pods and PostgreSQL. This approach eliminates the security risks of storing database credentials while leveraging Entra ID's identity platform. Familiarizing yourself with these building blocks will make the actual implementation much easier to follow and troubleshoot.
What is an OIDC Issuer?
An OpenID Connect (OIDC) issuer is a service that issues and validates identity tokens. In the context of AKS, the OIDC issuer provides a way for Kubernetes service accounts to be authenticated by Entra ID through federated identity credentials. For Example: AKS cluster's OIDC issuer enables pods to prove their identity to Entra ID without storing database passwords in the application code.
What are Federated Credentials?
Federated credentials establish a trust relationship between an Entra ID application or managed identity and an external identity provider. They define which external identities can impersonate the Entra ID identity. For Example: When the pod needs to connect to PostgreSQL, federated credentials allow the Kubernetes service account to "become" the managed identity, which can then authenticate to the PostgreSQL server using Entra ID authentication.
What is a Managed Identity?
A managed identity is an Entra ID identity that is automatically managed by Azure. It eliminates the need for developers to manage credentials by providing an identity for applications to use when connecting to resources that support Entra ID authentication. For Example: The managed identity serves as the application's database user in Entra ID. Instead of creating a traditional PostgreSQL user with a password, you assign the managed identity appropriate database permissions.
What is AKS Workload Identity?
AKS workload identity is a feature that enables Kubernetes pods to authenticate to Azure services using Entra ID identities. It uses OIDC federation to establish trust between the Kubernetes cluster and Entra ID, allowing pods to obtain Entra ID tokens using their Kubernetes service account. For Example: When a pod with workload identity starts up, it automatically receives an Entra ID token that can be used to authenticate to PostgreSQL as the configured managed identity user.
What is Workload Identity Federation?
Workload identity federation allows external identity providers (like Kubernetes) to exchange their tokens for Entra ID tokens without storing long-lived credentials. This enables secure access to Azure resources from workloads running outside of Azure. For Example: This eliminates the need to store PostgreSQL passwords in Kubernetes secrets. the pod's service account token is exchanged for an Entra ID token that PostgreSQL recognizes for authentication.
What is Kubernetes Service Accounts?
A Kubernetes service account provides an identity for processes that run in a pod. When pods need to communicate with the Kubernetes API server or external services, they use service accounts for authentication. In the context of workload identity, service accounts are linked to Entra ID identities through annotations, enabling pods to authenticate to Azure services without storing credentials. For Example: The service account acts as the pod's database identity card. By annotating it with workload identity configuration, you're telling AKS "when pods use this service account, let them authenticate to PostgreSQL as this specific managed identity user."
Prerequisites
- A well-configured AKS cluster with a supported Kubernetes version (workload identity is generally available on all of them)
- Azure CLI 2.47.0 or later, installed and signed in
- kubectl command-line tool installed
- A well-configured Azure Database for PostgreSQL Flexible Server with databases
- Entra ID permissions to create and manage managed identities
- Contributor or Owner role on the Azure subscription
- Basic understanding of Kubernetes concepts (pods, service accounts, deployments)
- Docker image of the application ready to deploy
Architecture Overview
The following diagram illustrates the high-level architecture and authentication flow for AKS workload identity with PostgreSQL:
flowchart LR
subgraph AZ["Azure"]
subgraph ENTRA["Microsoft Entra ID"]
MI["Managed identity<br/>myAppIdentity"]
FIC["Federated credential<br/>issuer + subject"]
ADM["DBA group<br/>PostgreSQL AD admin"]
end
subgraph AKS["AKS cluster"]
ISS["OIDC issuer<br/>(public signing keys)"]
WH["Workload identity<br/>mutating webhook"]
subgraph NS["namespace default"]
SA["Service account<br/>postgresql-workload-identity-sa<br/>annotation: client-id"]
POD["App pod<br/>label: azure.workload.identity/use<br/>projected token + AZURE_* env"]
end
end
subgraph PG["PostgreSQL Flexible Server"]
ROLE["Role myAppIdentity<br/>(pgaadauth_create_principal)"]
DB["mydatabase"]
end
end
FIC -->|belongs to| MI
FIC -->|trusts| ISS
FIC -->|subject matches| SA
POD -->|uses| SA
WH -->|injects token + env| POD
POD -->|exchange projected token| ENTRA
ENTRA -->|access token for MI| POD
POD -->|token as password, TLS| ROLE
ROLE -->|grants| DB
ADM -->|creates| ROLE
Authentication Flow Details
-
Token Request: When the application pod starts, the kubelet mounts a service account token, signed by the Kubernetes API server, into the pod. The AKS OIDC issuer publishes the keys that prove the token is genuine.
-
Token Exchange: The workload identity system automatically exchanges the Kubernetes service account token for an Entra ID access token using the federated credential configuration established between the AKS cluster and Entra ID.
-
Token Validation: Entra ID validates the token by:
- Verifying it came from the trusted OIDC issuer (AKS cluster)
- Confirming the service account subject matches the federated credential
- Issuing an Entra ID token for the managed identity
-
Database Authentication: The application uses the Entra ID token for authentication when connecting to PostgreSQL, which validates it against Entra ID and allows the connection.
Key Components
- OIDC Issuer: Provides the trust anchor between AKS and Entra ID
- Service Account: Links the pod to the managed identity through annotations
- Managed Identity: Acts as the database user in Entra ID (no password needed)
- Federated Credential: Establishes the trust relationship between the service account and managed identity
- PostgreSQL AD Admin: Configures the database to accept Entra ID authentication
This architecture eliminates credential management by using cryptographic tokens and trust relationships instead of storing passwords or connection strings in the application or Kubernetes secrets.
Authentication Sequence Diagram
The following sequence diagram illustrates the detailed step-by-step authentication flow when a pod connects to PostgreSQL using workload identity:
sequenceDiagram
autonumber
participant API as Kubernetes API server
participant WH as Workload identity webhook
participant K as kubelet
participant P as App pod
participant E as Microsoft Entra ID
participant ISS as AKS OIDC issuer
participant PG as PostgreSQL
API->>WH: pod create (label azure.workload.identity/use)
WH-->>API: inject AZURE_* env + projected token volume
K->>API: request service account token (audience api://AzureADTokenExchange)
API-->>K: signed JWT
K->>P: mount token at AZURE_FEDERATED_TOKEN_FILE
P->>E: exchange JWT for token (scope ossrdbms-aad)
E->>ISS: fetch signing keys (cached)
E->>E: match issuer + subject to federated credential
E-->>P: access token for the managed identity
P->>PG: connect as myAppIdentity, token as password (TLS)
PG->>PG: verify token, map to role myAppIdentity
PG-->>P: connection established, queries run with the role's grants
Sequence Flow Explanation:
- Pod Initialization (1–2): When the pod is created, the
azure.workload.identity/use: "true"label makes the webhook inject theAZURE_*environment variables and a projected service account token volume. - Service Account Token (3–5): The kubelet requests a token for the pod's service account from the API server and mounts the signed JWT in the pod. The OIDC issuer is not called here; it only publishes the public keys Entra ID uses to verify the token.
- Token Exchange (6–9): The application (through
DefaultAzureCredential) sends the JWT to Entra ID. Entra ID verifies the signature with the issuer's keys, matches issuer and subject to the federated credential, and returns an access token for the managed identity. - Database Connection (10–12): The application connects as
myAppIdentitywith the token as password. PostgreSQL verifies the token, maps it to the role created in Step 5, and runs queries with that role's grants.
Key Point: The azure.workload.identity/use: "true" label is essential - it signals the workload identity mutating webhook to automatically inject the necessary environment variables (AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_FEDERATED_TOKEN_FILE) and mount the projected service account token, enabling automatic token exchange through federated credentials without manual configuration.
This sequence eliminates traditional password-based authentication and provides secure, token-based access to PostgreSQL.
Step 1: Enable Workload Identity on AKS
The first step is configuring the AKS cluster to support workload identity authentication. By default, AKS clusters don't have this feature enabled, which means pods cannot authenticate to Azure services using managed identities.
Enabling workload identity requires both the workload identity addon and an OIDC issuer. The OIDC issuer establishes the trust relationship between Kubernetes and Entra ID, acting as the identity provider that Entra ID can verify and trust. Think of this as installing a "passport system" for the cluster - just like you need a passport office to issue passports for international travel, the cluster needs an OIDC issuer to provide identity tokens that Entra ID recognizes for PostgreSQL authentication.
Using Azure CLI
# Enable workload identity on existing cluster
az aks update \
--resource-group myResourceGroup \
--name myAKSCluster \
--enable-workload-identity \
--enable-oidc-issuer
Using Terraform
resource "azurerm_kubernetes_cluster" "aks" {
name = "myAKSCluster"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
workload_identity_enabled = true
oidc_issuer_enabled = true
# ... other configuration
}
Verification Commands
# Verify workload identity is enabled
az aks show -g myResourceGroup -n myAKSCluster --query "securityProfile.workloadIdentity.enabled" -o tsv
# Expected output: true
# Verify OIDC issuer is enabled and get the URL
az aks show -g myResourceGroup -n myAKSCluster --query "oidcIssuerProfile.issuerUrl" -o tsv
# Expected output: https://oidc.prod-aks.azure.com/[tenant-id]/[unique-id]/
Step 2: Create User-Assigned Managed Identity
The next step involves creating the Entra ID identity that enables passwordless authentication to PostgreSQL, completely eliminating traditional username/password credentials. PostgreSQL with Entra ID authentication requires an Entra ID principal to connect, and the managed identity fulfills this requirement.
This is essentially creating a "service account" in Entra ID specifically for the application. Just like you might create a dedicated database user for an application, you're creating a dedicated Entra ID identity. The key difference is this identity doesn't have a password - it uses cryptographic tokens for passwordless authentication, eliminating the need to store or manage any credentials in the application or Kubernetes secrets.
# Create a user-assigned managed identity
az identity create \
--name myAppIdentity \
--resource-group myResourceGroup \
--location myLocation
# Get the identity client ID
export USER_ASSIGNED_CLIENT_ID="$(az identity show --name myAppIdentity --resource-group myResourceGroup --query 'clientId' -o tsv)"
Verification Commands
# Verify the managed identity was created successfully
az identity show --name myAppIdentity --resource-group myResourceGroup --query '{name:name, clientId:clientId, principalId:principalId, resourceGroup:resourceGroup}' -o table
# Expected output: Table showing identity details
# List all managed identities in the resource group
az identity list --resource-group myResourceGroup --query '[].{name:name, clientId:clientId}' -o table
# Verify environment variable is set
echo "CLIENT_ID: $USER_ASSIGNED_CLIENT_ID"
# Expected output: CLIENT_ID: [guid-format-client-id]
Step 3: Create Kubernetes Service Account
The Kubernetes service account acts as the bridge between the pods and the Azure managed identity. Pods need a way to signal that they want to use workload identity for authentication, and the service account provides this mechanism through specific annotations that tell the workload identity system which Azure identity to use.
Think of this as giving the pod a passport that identifies it as belonging to a specific country (managed identity) and having the right to travel to certain destinations (database access). When the pod starts, Kubernetes sees this passport and automatically provides the necessary authentication tokens.
Create the service account with workload identity annotations:
# postgresql-service-account.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: postgresql-workload-identity-sa
namespace: default
annotations:
azure.workload.identity/client-id: <USER_ASSIGNED_CLIENT_ID>
Note
The azure.workload.identity/use: "true" label belongs on the pod (Step 6), not on the service account. The webhook ignores it here.
Apply the service account:
Verification Commands
# Verify the service account was created with correct annotations
kubectl get serviceaccount postgresql-workload-identity-sa -n default -o yaml
# Expected output: ServiceAccount with azure.workload.identity annotations
# Check service account annotations specifically
kubectl get serviceaccount postgresql-workload-identity-sa -n default -o jsonpath='{.metadata.annotations}' | jq
# Expected output: JSON showing the azure.workload.identity/client-id annotation
# List all service accounts in the namespace
kubectl get serviceaccounts -n default
# Expected output: List including postgresql-workload-identity-sa
# Verify the client ID annotation matches your managed identity
kubectl get serviceaccount postgresql-workload-identity-sa -n default -o jsonpath='{.metadata.annotations.azure\.workload\.identity/client-id}'
echo ""
echo "Expected: $USER_ASSIGNED_CLIENT_ID"
Step 4: Create Federated Identity Credential
Federated credentials establish the trust relationship between the Kubernetes service account and the Azure managed identity - this is the core of workload identity federation. Entra ID needs explicit permission to trust tokens from the AKS cluster, and the federated credential provides this by saying "if a token comes from this specific OIDC issuer (cluster) and claims to be this specific service account, then treat it as this managed identity."
This is like registering the country's passport system with international border control. You're telling Entra ID "when someone presents a passport from our Kubernetes cluster claiming to be the 'postgresql-workload-identity-sa' service account from the default namespace, trust them as if they're our managed identity citizen."
The OIDC issuer URL is a unique identifier that Entra ID uses to verify identity tokens are coming from the specific AKS cluster. Each AKS cluster has a unique issuer URL that serves as its "digital fingerprint" in the identity federation process. Think of this URL as the official address of the cluster's passport office - when the pod presents an identity token to PostgreSQL, Entra ID checks this URL to confirm the token came from the trusted cluster before allowing database access.
Using Azure CLI
# Get the OIDC issuer URL from the AKS cluster
export AKS_OIDC_ISSUER="$(az aks show -n myAKSCluster -g myResourceGroup --query "oidcIssuerProfile.issuerUrl" -o tsv)"
echo $AKS_OIDC_ISSUER
# Create federated identity credential
az identity federated-credential create \
--name myAppFederatedCredential \
--identity-name myAppIdentity \
--resource-group myResourceGroup \
--issuer $AKS_OIDC_ISSUER \
--subject system:serviceaccount:default:postgresql-workload-identity-sa
Using Terraform
# Get the OIDC issuer URL from the AKS cluster
data "azurerm_kubernetes_cluster" "aks" {
name = "myAKSCluster"
resource_group_name = "myResourceGroup"
}
# Reference the existing managed identity
data "azurerm_user_assigned_identity" "app_identity" {
name = "myAppIdentity"
resource_group_name = "myResourceGroup"
}
# Create federated identity credential
resource "azurerm_federated_identity_credential" "app_federated_credential" {
name = "myAppFederatedCredential"
resource_group_name = data.azurerm_user_assigned_identity.app_identity.resource_group_name
audience = ["api://AzureADTokenExchange"]
issuer = data.azurerm_kubernetes_cluster.aks.oidc_issuer_url
parent_id = data.azurerm_user_assigned_identity.app_identity.id
subject = "system:serviceaccount:default:postgresql-workload-identity-sa"
}
Note: The audience is set to ["api://AzureADTokenExchange"] which is the standard audience for Entra ID workload identity federation. The subject follows the Kubernetes service account format: system:serviceaccount:<namespace>:<service-account-name>.
Verification Commands
# Verify the federated credential was created successfully
az identity federated-credential show \
--name myAppFederatedCredential \
--identity-name myAppIdentity \
--resource-group myResourceGroup \
--query '{name:name, issuer:issuer, subject:subject, audience:audiences}' -o table
# List all federated credentials for the managed identity
az identity federated-credential list \
--identity-name myAppIdentity \
--resource-group myResourceGroup \
--query '[].{name:name, subject:subject, issuer:issuer}' -o table
# Verify the OIDC issuer URL matches
echo "OIDC Issuer from cluster: $AKS_OIDC_ISSUER"
az identity federated-credential show \
--name myAppFederatedCredential \
--identity-name myAppIdentity \
--resource-group myResourceGroup \
--query 'issuer' -o tsv
# Expected output: Both URLs should match
# Verify the subject format is correct
az identity federated-credential show \
--name myAppFederatedCredential \
--identity-name myAppIdentity \
--resource-group myResourceGroup \
--query 'subject' -o tsv
# Expected output: system:serviceaccount:default:postgresql-workload-identity-sa
Step 5: Configure PostgreSQL Access
Now you need to grant the managed identity access to the PostgreSQL server. Even though you have a managed identity, PostgreSQL doesn't automatically know about it. You enable Entra ID authentication on the server, set an Entra ID administrator (a person or group, not the application), and then that administrator creates a database role for the managed identity.
This is essentially adding the service account to the database's user directory. You're telling PostgreSQL "this Entra ID identity is authorized to connect, and when it does, treat it as a legitimate database user with appropriate permissions."
Don't make the application identity the server admin
The Entra ID administrator can create roles and databases. Giving that to the application breaks least privilege. Use a DBA group as admin and give the application only the grants it needs.
# Enable Entra ID (Microsoft Entra) authentication on the server
az postgres flexible-server update \
--resource-group myResourceGroup \
--name myPostgreSQLServer \
--microsoft-entra-auth Enabled
# Set an Entra ID group of DBAs as administrator
az postgres flexible-server ad-admin set \
--resource-group myResourceGroup \
--server-name myPostgreSQLServer \
--object-id <DBA_GROUP_OBJECT_ID> \
--display-name my-postgres-admins \
--type Group
Using Terraform
resource "azurerm_postgresql_flexible_server" "pg" {
# ... other configuration
authentication {
active_directory_auth_enabled = true
password_auth_enabled = false
tenant_id = data.azurerm_client_config.current.tenant_id
}
}
resource "azurerm_postgresql_flexible_server_active_directory_administrator" "admin" {
server_name = azurerm_postgresql_flexible_server.pg.name
resource_group_name = azurerm_postgresql_flexible_server.pg.resource_group_name
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = "<DBA_GROUP_OBJECT_ID>"
principal_name = "my-postgres-admins"
principal_type = "Group"
}
Then sign in as a member of the admin group and create the role for the managed identity. A plain CREATE USER creates a password role that can't sign in with a token; Entra ID roles must be created with pgaadauth_create_principal, from the postgres database:
-- Run in the postgres database, signed in as the Entra ID admin
-- Arguments: role name (must match the managed identity name), is_admin, is_mfa
SELECT * FROM pgaadauth_create_principal('myAppIdentity', false, false);
-- Then, in the application database
GRANT CONNECT ON DATABASE mydatabase TO "myAppIdentity";
GRANT USAGE ON SCHEMA public TO "myAppIdentity";
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO "myAppIdentity";
-- Covers tables created later by the role running this statement
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO "myAppIdentity";
Verification Commands
# Verify the Entra ID admin
az postgres flexible-server ad-admin list \
--resource-group myResourceGroup \
--server-name myPostgreSQLServer \
-o table
# Check if Entra ID authentication is enabled
az postgres flexible-server show \
--resource-group myResourceGroup \
--name myPostgreSQLServer \
--query 'authConfig.activeDirectoryAuth' -o tsv
# Expected output: Enabled
-- As the Entra ID admin: confirm the role exists and is an Entra ID principal
SELECT rolname, objectid, principaltype FROM pgaadauth_list_principals(false);
-- Expected: a row for myAppIdentity with principaltype 'service'
The end-to-end test with the managed identity's token is in Step 7, from inside the pod.
Step 6: Deploy the Application
This is where everything comes together. You need to configure the application deployment to use the workload identity service account and provide the necessary environment variables for Entra ID authentication to PostgreSQL. The pods must be explicitly configured to use the service account you created, and the application code needs to know the Azure client ID and tenant ID to properly authenticate with Entra ID before connecting to PostgreSQL.
Notice that you're providing the managed identity name as the database user, but no password - the application fetches an Entra ID token at run time and sends it as the password (see "Application code" below). You're essentially telling Kubernetes "when you run this pod, give it the identity (service account) we set up, and the federated credential system will handle token exchange to prove its identity to PostgreSQL."
Key Workload Identity Configuration Points:
# api-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: dotnet-api
namespace: default
spec:
replicas: 2
selector:
matchLabels:
app: dotnet-api
template:
metadata:
labels:
app: dotnet-api
# 🔑 REQUIRED: This label tells the workload identity webhook to inject environment variables
azure.workload.identity/use: "true"
spec:
# 🔑 REQUIRED: Reference the workload identity service account
serviceAccountName: postgresql-workload-identity-sa
containers:
- name: api-app
image: your-registry.azurecr.io/myapp-api:1.0.0 # pin a version, not :latest
ports:
- containerPort: 8080
env:
# 🔑 APPLICATION-SPECIFIC: Connection string uses managed identity name as username, NO PASSWORD
- name: DATABASE_URL
value: "Host=myPostgreSQLServer.postgres.database.azure.com;Database=mydatabase;Username=myAppIdentity;SSL Mode=Require;"
# Note: AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_FEDERATED_TOKEN_FILE are automatically
# injected by the workload identity webhook when azure.workload.identity/use: "true" label is present
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
Critical Configuration Changes:
serviceAccountName: postgresql-workload-identity-sa- Links the pod to the workload identity service account- Automatic Environment Variable Injection - The workload identity webhook automatically injects
AZURE_CLIENT_ID,AZURE_TENANT_ID, andAZURE_FEDERATED_TOKEN_FILEwhen the pod has theazure.workload.identity/use: "true"label - Connection String - Uses the managed identity name (
myAppIdentity) as the username with no password specified
Important: The azure.workload.identity/use: "true" label is required on the pod template (in the Deployment). It tells the workload identity mutating webhook which pods to inject configuration into. The webhook looks for this label to:
- Inject environment variables (AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_FEDERATED_TOKEN_FILE)
- Mount the projected service account token at /var/run/secrets/azure/tokens/azure-identity-token
- Configure the pod for automatic token exchange
The webhook injects the configuration, but it does not connect to the database for you. The application must request a token and use it as the password.
Application code
Npgsql does not fetch Entra ID tokens on its own. With Azure.Identity, DefaultAzureCredential reads the injected AZURE_* variables and performs the token exchange. Tokens expire after about an hour, so use a password provider that refreshes them:
using Azure.Core;
using Azure.Identity;
using Npgsql;
var credential = new DefaultAzureCredential();
var tokenRequest = new TokenRequestContext(
new[] { "https://ossrdbms-aad.database.windows.net/.default" });
var builder = new NpgsqlDataSourceBuilder(Environment.GetEnvironmentVariable("DATABASE_URL"));
builder.UsePeriodicPasswordProvider(
async (_, ct) => (await credential.GetTokenAsync(tokenRequest, ct)).Token,
TimeSpan.FromMinutes(55), // refresh before the token expires
TimeSpan.FromSeconds(5)); // retry interval on failure
await using var dataSource = builder.Build();
Verification Commands
# Apply the deployment
kubectl apply -f api-deployment.yaml
# Verify the deployment was created successfully
kubectl get deployment dotnet-api -n default -o wide
# Expected output: Deployment with READY status
# Check if pods are running with the correct service account
kubectl get pods -n default -l app=dotnet-api -o jsonpath='{.items[*].spec.serviceAccountName}'
# Expected output: postgresql-workload-identity-sa
# Check pod events for any issues
kubectl describe pods -n default -l app=dotnet-api
# Verify workload identity webhook injected the necessary volumes and environment variables
kubectl get pods -n default -l app=dotnet-api -o yaml | grep -A 10 -B 10 "azure-identity-token"
# Check if the pod has the projected service account token
kubectl exec -it deployment/dotnet-api -n default -- ls -la /var/run/secrets/azure/tokens/
# Verify injected environment variables (automatically added by webhook)
kubectl exec -it deployment/dotnet-api -n default -- env | grep AZURE
Step 7: Verification
Finally, you need to validate that the entire workload identity chain is functioning correctly and the pods can successfully authenticate to PostgreSQL without credentials. Since workload identity involves multiple components working together (OIDC issuer, service accounts, federated credentials, managed identity, PostgreSQL AD admin), verification helps identify which component might be misconfigured if authentication fails.
Think of this as testing the passport system. You're checking that: 1) the passport is valid and recognized (token acquisition), 2) border control accepts the passport (Entra ID trusts the token), and 3) you can actually enter the country and access what you need (PostgreSQL connection).
# Check if workload identity is working
kubectl logs deployment/dotnet-api -n default
# Test connection from within the pod
kubectl exec -it deployment/dotnet-api -n default -- /bin/bash
# Inside the pod (needs the Azure CLI and psql, e.g. in a debug pod using the same service account):
# exchange the projected token for an Entra ID token
az login --service-principal \
-u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" \
--federated-token "$(cat "$AZURE_FEDERATED_TOKEN_FILE")"
# get a token for Azure Database for PostgreSQL and connect with it as the password
export PGPASSWORD="$(az account get-access-token --resource-type oss-rdbms --query accessToken -o tsv)"
psql "host=myPostgreSQLServer.postgres.database.azure.com dbname=mydatabase user=myAppIdentity sslmode=require" \
-c "SELECT current_user;"
# Expected output: myAppIdentity
Warning
Don't test with curl http://169.254.169.254/... (IMDS). That returns a token for the node's identity, not the workload identity, so it proves nothing about this setup.
Additional Verification Commands
# Check overall workload identity integration
kubectl get pods -n default -l app=dotnet-api -o jsonpath='{.items[0].metadata.labels.azure\.workload\.identity/use}'
# Expected output: true
# Verify the webhook mutations were applied
kubectl get mutatingwebhookconfiguration azure-wi-webhook-mutating-webhook-configuration -o yaml
# Check application logs for authentication success/failure
kubectl logs deployment/dotnet-api -n default --tail=50
# Verify end-to-end connectivity (if your app has a health endpoint)
kubectl port-forward deployment/dotnet-api 8080:8080 -n default &
sleep 5
curl -f http://localhost:8080/health || echo "Health check failed"
pkill -f "kubectl port-forward"
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
AADSTS70021: No matching federated identity record found |
Issuer or subject in the federated credential doesn't match the cluster or system:serviceaccount:<namespace>:<name> |
Compare with Step 4's verification output; fix namespace or service account name |
AZURE_* variables missing in the pod |
Pod label azure.workload.identity/use: "true" missing, or pod created before the service account annotation |
Add the label to the pod template and restart: kubectl rollout restart deployment/dotnet-api |
| Token exchange fails right after setup | Federated credential not yet propagated | Wait a few seconds and retry |
role "myAppIdentity" does not exist |
Role created with CREATE USER, or not created |
Create it with pgaadauth_create_principal (Step 5) |
password authentication failed |
App sends no token, or the role name doesn't match the identity name | Add the token provider (Step 6); use the managed identity's exact name as Username |
| Connection timeout | Networking, not identity: firewall or private access blocks the AKS subnet | Allow the AKS subnet or use private access with VNet integration |
Conclusion
AKS workload identity with federated credentials provides a secure, scalable solution for passwordless authentication between Kubernetes pods and Azure Database for PostgreSQL. By leveraging OIDC federation, managed identities, and federated identity credentials, you can completely eliminate password-based authentication while maintaining fine-grained access control.
This passwordless authentication approach significantly improves security by removing the need to store database passwords in application code or Kubernetes secrets, while providing seamless authentication through Entra ID integration and automatic token exchange via federated credentials. Organizations can now deploy applications with confidence, knowing that database credentials are never exposed or stored anywhere in the system.
References
- PostgreSQL Commands Cheat Sheet - Essential PostgreSQL commands and operations
- Workload identity overview
- Workload identity federation
- Azure Workload Identity project
- Azure Workload Identity quick start
- OIDC on AKS
- Deploy workload identity on AKS
- Azure Samples - Spring Boot samples
- Spring Boot passwordless demo
- Spring configuration for passwordless authentication
- Microsoft Entra authentication with PostgreSQL Flexible Server
- PostgreSQL Authentication with Managed Identity
- A great article about workload identity federation
- Connect your Kubernetes application to your database without any credentials (and securely)