Catalogue / entra-java-token-credentials
entra-java-token-credentials
Older skill: source not recordedSignedGuides an agent through selecting, building, and debugging Microsoft Entra ID TokenCredential implementations from the azure-identity library in Java, covering DefaultAzureCredential ordering and tuning, custom ChainedTokenCredential design, managed identity, workload identity federation, service-pr…--- name: entra-java-token-credentials description: > Guides an agent through selecting, building, and debugging Microsoft Entra ID TokenCredential implementations from the azure-identity library in Java, covering DefaultAzureCredential ordering and tuning, custom ChainedTokenCredential design, managed identity, workload identity federation, service-principal secret and certificate credentials, environment-variable sets, browser and device-code flows, credential-specific token caching, sovereign clouds, proxies, direct token acquisition, and failure diagnosis. Use when a Java application must authenticate to Azure services such as Key Vault, Storage, Cosmos DB, Event Hubs, or Service Bus, when choosing a credential for a specific deployment target, or when diagnosing CredentialUnavailableException or ClientAuthenticationException. Not for creating app registrations or role assignments, Spring Boot property configuration, or identity SDKs for other languages. license: MIT ---
Azure authentication for Java
Work through this as a chain of decisions: establish where the code runs, choose the credential that matches that reality, configure it without ever touching a secret's value, hand it to a service client, and read failures precisely. When a deployment fact is missing, ask the user rather than assuming it.
Confirm before anything leaves the machine
Constructing builders and clients is local and sends no network traffic. Everything below does leave the machine, so before triggering any of it, name the credential, the operation, and the target resource to the user and get an explicit yes:
- A token request, against Entra ID or a managed-identity endpoint.
- An interactive sign-in, where a browser page or device-code prompt waits for a human.
- Any call against a live Azure resource — read, list, write, delete, or send — including ones served from a token the SDK already holds.
When the effect is destructive or propagating (deleting a Key Vault secret, purging, publishing messages other systems consume), state the irreversible consequence inside the confirmation request itself.
Reference secrets, never values
You never need a secret's value, so never obtain one. Do not run or write anything that prints, decodes, or exports a client secret, PFX password, or PEM private key, and never copy such a value into code, tests, comments, or the conversation. Instead:
- Prefer credentials that resolve material themselves:
EnvironmentCredentialreads the standardAZURE_*variables; a no-argumentWorkloadIdentityCredentialreads the projected token file. - Where you must pass material, pass a reference the application resolves, e.g.
clientSecret(System.getenv("AZURE_CLIENT_SECRET")). - Tell the user which variable or store to populate, by name only, and leave filling it to them.
If a secret value surfaces anyway, stop, do not propagate it, and advise rotation.
Establish the deployment facts
Ask, as the conversation allows: where the code runs (laptop, VM, App Service, Functions, AKS pod, CI runner, container outside Azure); which identity exists there (system- or user-assigned managed identity, workload-identity federation, an app registration, a signed-in human); whether a human can sign in at runtime and whether a browser exists; which cloud (public, Government, China); and whether egress crosses a corporate proxy.
Add the library
Prefer the BOM so all Azure artifacts stay aligned, and declare azure-identity as a plain dependency inside the dependencies element:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-sdk-bom</artifactId>
<version>1.2.29</version> <!-- check Maven Central for the current release -->
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
</dependency>
</dependencies>Without a BOM, declare com.azure:azure-identity with an explicit version; Gradle users can import the BOM as a platform.
Match the situation to a credential
| Confirmed situation | Credential | Builder essentials | |---|---|---| | Azure-hosted compute with a platform identity | ManagedIdentityCredential | system-assigned: no-arg build(); user-assigned: exactly one of clientId(...), resourceId(...), objectId(...) | | AKS pod with a projected service-account token | WorkloadIdentityCredential | no-arg build() reads AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_FEDERATED_TOKEN_FILE; or set tenantId/clientId/tokenFilePath explicitly | | Automation outside Azure holding an app registration | ClientSecretCredential or ClientCertificateCredential | tenantId(...), clientId(...), then clientSecret(...) or pemCertificate(path) / pfxCertificate(path, password) (InputStream overloads exist); sendCertificateChain(true) for subject-name/issuer auth | | CI with variables injected into the environment | EnvironmentCredential | no-arg build(); variable sets below | | Developer machine with an existing CLI login | AzureCliCredential | tenantId(...) pins one tenant when several accounts are signed in | | Human present, browser available | InteractiveBrowserCredential | clientId(...), redirectUrl(...) matching the app registration | | Human present, no browser | DeviceCodeCredential | clientId(...) plus challengeConsumer(challenge -> System.out.println(challenge.getMessage())) | | One artifact across several targets | DefaultAzureCredential or a custom chain | following sections |
Variables behind EnvironmentCredential
AZURE_TENANT_ID and AZURE_CLIENT_ID are required in every set; a third variable selects the mode:
| Additional variables | Mode | |---|---| | AZURE_CLIENT_SECRET | secret-based service principal (takes precedence when present) | | AZURE_CLIENT_CERTIFICATE_PATH, optional AZURE_CLIENT_CERTIFICATE_PASSWORD | certificate-based service principal | | AZURE_USERNAME with AZURE_PASSWORD | username/password principal |
Two cautions: build() succeeds even with no complete set, surfacing the gap only as CredentialUnavailableException at token time — a clean build validates nothing. And the variable names must match exactly; abbreviations silently disable that mode.
The default chain
In the 1.18.x line, DefaultAzureCredential tries EnvironmentCredential, WorkloadIdentityCredential, ManagedIdentityCredential, AzureDeveloperCliCredential, IntelliJCredential, AzureCliCredential, then AzurePowerShellCredential. Membership has shifted across 1.x releases, so confirm the list in the README of the version the project pins.
Failure handling is asymmetric:
- A member that returns a token ends the chain.
- A member reporting itself unusable raises
CredentialUnavailableExceptioninternally and the chain continues. - The deployed members — environment, workload identity, managed identity — count as deliberate configuration: when one genuinely attempts authentication and Entra ID refuses (
ClientAuthenticationException, e.g. expired secret, wrong tenant), the chain halts and the error propagates. A staleAZURE_CLIENT_SECRETwill not fall through to a CLI login. - Developer-tool members are treated leniently: an authentication failure from one counts as unavailability and the chain moves on.
- If nothing could even attempt sign-in, you receive one
CredentialUnavailableExceptionsummarizing the attempts.
Tuning: managedIdentityClientId(...) to select a user-assigned identity, tenantId(...) to pin a tenant, and exclusion methods such as excludeAzureCliCredential() or excludeIntelliJCredential() (each member has one) so an ambient developer login cannot hijack a server deployment:
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
.managedIdentityClientId("6e0d41af-2c9b-47f5-8a1e-93d7c2fbe50b")
.excludeAzureCliCredential()
.build();
SecretClient secrets = new SecretClientBuilder()
.vaultUrl("https://kv-quotes-engine-prod.vault.azure.net")
.credential(credential)
.buildClient();Designing a custom chain
Reach for ChainedTokenCredential when the membership or failure policy above does not fit. Ordering is the whole design: addFirst inserts at the front, addLast appends, members run in that order, first success wins. Two consequences: an early member can mask a later one you expected to be used, so trace which member actually produced the token; and a custom chain applies no deployed-versus-developer leniency — the first member that genuinely attempts and is refused stops the chain with ClientAuthenticationException, so put credentials whose failure should be fatal early.
This example backs an internal reporting tool deployed three ways — an AKS CronJob, a certified container outside Azure holding a certificate, and analysts' laptops:
ChainedTokenCredentialBuilder chain = new ChainedTokenCredentialBuilder()
.addLast(new WorkloadIdentityCredentialBuilder().build()); // pods win, zero config
String pem = System.getenv("REPORTER_CERT_PATH");
if (pem != null) { // guard: this builder validates required fields at build()
chain.addLast(new ClientCertificateCredentialBuilder()
.tenantId(System.getenv("REPORTER_TENANT_ID"))
.clientId(System.getenv("REPORTER_CLIENT_ID"))
.pemCertificate(pem)
.build());
}
ChainedTokenCredential credential = chain
.addLast(new InteractiveBrowserCredentialBuilder()
.clientId("d84b2f60-7a13-4c55-9e26-b9f0e1a7c4d2")
.redirectUrl("http://localhost:8412")
.build())
.build();Token caching: check the credential type before promising reuse
Caching is not uniform across the library — match your guidance to the credential:
| Credential | Caching behavior | |---|---| | ClientSecretCredential, ClientCertificateCredential, UsernamePasswordCredential, OnBehalfOfCredential, ManagedIdentityCredential, WorkloadIdentityCredential | Keep an in-memory token cache per instance and re-request only near expiry | | EnvironmentCredential | Wraps one of the above per the variables present; caches like the wrapped type | | AzureCliCredential, AzurePowerShellCredential, AzureDeveloperCliCredential | No instance-level cache: every token request invokes the external tool, and any reuse comes from the tool's own token store — so repeated acquisitions pay process-start cost each time regardless of instance reuse | | InteractiveBrowserCredential, DeviceCodeCredential | In-memory only unless you opt into persistent caching |
Practical guidance: construct caching credentials once, as a static or long-lived field, share them across clients, and reuse those clients — per-operation construction discards the in-memory cache and forces a full authority round trip. For the tool-backed types, instance reuse adds no caching; keep them long-lived for hygiene, but set the expectation that each token acquisition spawns the tool.
SharedTokenCacheCredential
This credential authenticates against the MSAL shared token cache on the local machine. The producers Microsoft supports for that cache are Visual Studio (Windows) and Visual Studio Code with the Azure Account extension — it does not read the Azure CLI's or IntelliJ's separate token stores, and sign-ins made with those tools are reached through AzureCliCredential and IntelliJCredential instead, so never promise reuse of those logins here. Builder behavior: clientId(...) names the application whose cached tokens to reuse; when the cache holds multiple accounts, set username(...) to select one — with several accounts cached and no username supplied, the credential cannot choose and authentication fails; an empty cache surfaces as CredentialUnavailableException.
Preview shortened. The full SKILL.md is in the pack.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 17.4 kB | 83069aa61bdd |
| THIRD_PARTY_NOTICES.md | 1.5 kB | 922d6d30f43d |
| examples.json | 2.6 kB | 0f0051f3fc68 |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.0 Current | Not recorded | 12 Oct 2026 |
Locking a skill to one version needs Pro.