From b91d08d9aad2b203a8f0732a04396e74590be896 Mon Sep 17 00:00:00 2001
From: Victor Colin Amador
Date: Tue, 20 Oct 2026 01:42:39 -0700
Subject: [PATCH 01/11] Add GitHub Actions credential to Azure Identity
---
sdk/identity/azure-identity/CHANGELOG.md | 1 +
sdk/identity/azure-identity/README.md | 53 +++
.../azure-identity/TROUBLESHOOTING.md | 21 ++
.../identity/GitHubActionsCredential.java | 172 +++++++++
.../GitHubActionsCredentialBuilder.java | 170 +++++++++
.../credential/JavaDocCodeSnippets.java | 22 ++
.../GitHubActionsCredentialBuilderTest.java | 160 +++++++++
.../identity/GitHubActionsCredentialTest.java | 339 ++++++++++++++++++
8 files changed, 938 insertions(+)
create mode 100644 sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java
create mode 100644 sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredentialBuilder.java
create mode 100644 sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialBuilderTest.java
create mode 100644 sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java
diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md
index 9b662e4e4fece..e842901ffe19c 100644
--- a/sdk/identity/azure-identity/CHANGELOG.md
+++ b/sdk/identity/azure-identity/CHANGELOG.md
@@ -4,6 +4,7 @@
### Features Added
+- Added `GitHubActionsCredential` and `GitHubActionsCredentialBuilder` for authentication using GitHub Actions OIDC federation.
- Added support for user-assigned managed identities on Azure Arc in `ManagedIdentityCredential` and `DefaultAzureCredential`.
### Breaking Changes
diff --git a/sdk/identity/azure-identity/README.md b/sdk/identity/azure-identity/README.md
index 40a5114a066a7..80a8cd3e1884d 100644
--- a/sdk/identity/azure-identity/README.md
+++ b/sdk/identity/azure-identity/README.md
@@ -204,6 +204,7 @@ Not all credentials honor this configuration. Credentials that authenticate thro
| Credential | Usage | Example | Reference |
|-----------------------------------------|-------------------------------------------------------------------|-----------------------------|--------------------------------------------|
| [AzurePipelinesCredential][cred_apc] | Authenticates with a service connection in Azure Pipelines. | | [Manage service connections][cred_apc_ref] |
+| [GitHubActionsCredential](#authenticate-github-actions-workflows) | Authenticates a GitHub Actions workflow using OIDC federation | [example](#authenticate-github-actions-workflows) | [Configure federation with Azure][github_oidc] |
| [ClientAssertionCredential][cred_cac] | Authenticates a service principal using a signed client assertion | | |
| [ClientCertificateCredential][cred_ccc] | Authenticates a service principal using a certificate | [example][cred_ccc_example] | [Service principal authentication][sp] |
| [ClientSecretCredential][cred_csc] | Authenticates a service principal using a secret | [example][cred_csc_example] | [Service principal authentication][sp] |
@@ -229,6 +230,57 @@ Not all credentials honor this configuration. Credentials that authenticate thro
> __Note:__ All credential implementations in the Azure Identity library are threadsafe, and a single credential instance can be used to create multiple service clients.
+## Authenticate GitHub Actions workflows
+
+`GitHubActionsCredential` exchanges a GitHub Actions OIDC token for a Microsoft Entra access token.
+Configure a federated identity credential on your Entra application that trusts the workflow's issuer,
+subject, and audience. Follow [GitHub's Azure OIDC setup guide][github_oidc], then set these workflow permissions
+and environment variables:
+
+```yaml
+permissions:
+ contents: read
+ id-token: write
+
+env:
+ AZURE_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
+ AZURE_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }}
+```
+
+GitHub provides `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN` to the workflow step.
+Do not configure those values as repository secrets or print them. No client secret, certificate, or
+`azure/login` step is required for this credential.
+
+```java readme-sample-github-actions-credential
+TokenCredential gitHubCredential = new GitHubActionsCredentialBuilder().build();
+```
+
+You can override the Azure IDs without changing the runner-provided OIDC configuration:
+
+```java readme-sample-github-actions-credential-explicit
+TokenCredential explicitCredential = new GitHubActionsCredentialBuilder()
+ .tenantId("")
+ .clientId("")
+ .build();
+```
+
+The effective authority is the builder's `authorityHost`, followed by `AZURE_AUTHORITY_HOST`, then Azure Public.
+The credential derives the assertion audience from that authority. Configure the same audience in the federated
+identity credential:
+
+| Authority host | Audience |
+| --- | --- |
+| `https://login.microsoftonline.com/` | `api://AzureADTokenExchange` |
+| `https://login.chinacloudapi.cn/` | `api://AzureADTokenExchangeChina` |
+| `https://login.microsoftonline.us/` | `api://AzureADTokenExchangeUSGov` |
+| `https://login.sovcloud-identity.fr/` | `api://AzureADTokenExchangeFrance` |
+| `https://login.sovcloud-identity.de/` | `api://AzureADTokenExchangeGermany` |
+| `https://login.sovcloud-identity.sg/` | `api://AzureADTokenExchangeGovSG` |
+
+Unsupported authorities fail rather than defaulting to the public-cloud audience. Missing configuration fails
+during `build()`, before a token request is attempted. This standalone credential is not part of
+`DefaultAzureCredential`.
+
## Environment variables
`DefaultAzureCredential` and `EnvironmentCredential` can be configured with environment variables. Each type of authentication requires values for specific variables.
@@ -344,6 +396,7 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con
[cred_wic_example]: https://learn.microsoft.com/azure/aks/workload-identity-overview?tabs=java#azure-identity-client-libraries
[cred_wic_ref]: https://learn.microsoft.com/azure/aks/workload-identity-overview
[entraid_doc]: https://learn.microsoft.com/entra/identity/
+[github_oidc]: https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-azure
[javadoc]: https://learn.microsoft.com/java/api/com.azure.identity?view=azure-java-stable
[jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
[secrets_client_library]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/keyvault/azure-security-keyvault-secrets
diff --git a/sdk/identity/azure-identity/TROUBLESHOOTING.md b/sdk/identity/azure-identity/TROUBLESHOOTING.md
index f58d827abe549..d64f399a7310a 100644
--- a/sdk/identity/azure-identity/TROUBLESHOOTING.md
+++ b/sdk/identity/azure-identity/TROUBLESHOOTING.md
@@ -23,6 +23,7 @@ This troubleshooting guide covers failure investigation techniques, common error
- [Troubleshoot IntelliJCredential authentication issues](#troubleshoot-intellijcredential-authentication-issues)
- [Troubleshoot VisualStudioCodeCredential authentication issues](#troubleshoot-visualstudiocodecredential-authentication-issues)
- [Troubleshoot AzurePipelinesCredential authentication issues](#troubleshoot-azurepipelinescredential-authentication-issues)
+- [Troubleshoot GitHubActionsCredential authentication issues](#troubleshoot-githubactionscredential-authentication-issues)
- [Troubleshoot authentication timeout issues](#troubleshoot-authentication-timeout-issues)
- [Troubleshoot Web Account Manager (WAM) brokered authentication issues](#troubleshoot-web-account-manager-wam-brokered-authentication-issues)
- [Get additional help](#get-additional-help)
@@ -313,6 +314,26 @@ As of version 1.17.0-beta.1, `VisualStudioCodeCredential` uses broker authentica
|AADSTS700016: Application with identifier 'clientId' was not found in the directory 'Microsoft'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.|The `` provided is invalid|Verify the client ID argument is valid. If the service connection's federated identity was registered via a user-assigned managed identity, the client ID of the managed identity should be provided. If the service connection's federated identity is registered via an app registration, the Application (client) ID from your app registration should be provided.|
+## Troubleshoot `GitHubActionsCredential` authentication issues
+
+`GitHubActionsCredential` is a standalone credential for GitHub Actions OIDC federation. It is not part of
+`DefaultAzureCredential`. Missing configuration fails during `GitHubActionsCredentialBuilder.build()`, so
+constructing an unconfigured credential does not defer failure to a manually composed credential chain.
+
+| Error | Cause | Mitigation |
+| --- | --- | --- |
+| `CredentialUnavailableException` naming `AZURE_CLIENT_ID` or `AZURE_TENANT_ID` | The Azure application IDs are missing. | Set the environment variables or call `clientId` and `tenantId` on the builder. |
+| `CredentialUnavailableException` naming `ACTIONS_ID_TOKEN_REQUEST_URL` or `ACTIONS_ID_TOKEN_REQUEST_TOKEN` | The process is outside an OIDC-enabled workflow step. | Grant the job `permissions: id-token: write` and run the SDK in that GitHub Actions step. Do not supply the runner token manually. |
+| Invalid runner request URL | The configured URL is not an absolute HTTPS URL, or contains user information or a fragment. | Use the URL supplied by the GitHub Actions runner. |
+| Unsupported authority host | There is no supported audience mapping for the authority. | Use one of the [documented cloud authorities](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity/README.md#authenticate-github-actions-workflows). Custom audiences and authorities are not supported. |
+| GitHub OIDC HTTP 401/403 | GitHub rejected the runner request. | Check the job's OIDC permissions and ensure the request variables belong to the current workflow step. |
+| Invalid GitHub assertion response | The response is not HTTP 200 with a nonempty string `value`. | Check connectivity and any proxy affecting the GitHub OIDC endpoint. Do not log the response body; it can contain an assertion. |
+| Entra reports no matching federated identity record | The presented issuer, subject, or audience does not match the app's federation configuration. | Match the actual claims for the repository/ref, including immutable subject IDs when applicable, and the audience derived from the authority host. |
+
+See [GitHub's Azure OIDC setup guide](https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-azure)
+for federation prerequisites. Never include the runner bearer token, OIDC assertion, access token, or raw token
+response in diagnostic logs.
+
## Troubleshoot multi-tenant authentication issues
`ClientAuthenticationException`
diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java
new file mode 100644
index 0000000000000..13aa8dd6d6bea
--- /dev/null
+++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java
@@ -0,0 +1,172 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.identity;
+
+import com.azure.core.annotation.Immutable;
+import com.azure.core.credential.AccessToken;
+import com.azure.core.credential.TokenCredential;
+import com.azure.core.credential.TokenRequestContext;
+import com.azure.core.exception.ClientAuthenticationException;
+import com.azure.core.http.HttpHeaderName;
+import com.azure.core.http.HttpMethod;
+import com.azure.core.http.HttpRequest;
+import com.azure.core.http.HttpResponse;
+import com.azure.core.util.Context;
+import com.azure.core.util.CoreUtils;
+import com.azure.core.util.logging.ClientLogger;
+import com.azure.identity.implementation.IdentityClient;
+import com.azure.identity.implementation.IdentityClientBuilder;
+import com.azure.identity.implementation.IdentityClientOptions;
+import com.azure.identity.implementation.IdentitySyncClient;
+import com.azure.identity.implementation.util.IdentityUtil;
+import com.azure.identity.implementation.util.LoggingUtil;
+import com.azure.json.JsonProviders;
+import com.azure.json.JsonReader;
+import com.azure.json.JsonToken;
+import reactor.core.publisher.Mono;
+import reactor.core.scheduler.Schedulers;
+
+import java.io.IOException;
+
+/**
+ * Authenticates an application in GitHub Actions using an OIDC federated identity credential.
+ *
+ * Configure a federated identity credential on the Microsoft Entra application that trusts the GitHub workflow's
+ * issuer, subject, and audience. The workflow needs {@code permissions: id-token: write}. GitHub supplies the
+ * OIDC request URL and bearer token. The client and tenant IDs default to {@code AZURE_CLIENT_ID} and
+ * {@code AZURE_TENANT_ID}; they can also be set on {@link GitHubActionsCredentialBuilder}.
+ *
+ * The assertion audience is selected from the authority host. This credential supports Azure Public, China,
+ * US Government, France Government, Germany Government, and Singapore Government. It is not included in
+ * {@link DefaultAzureCredential}.
+ *
+ *
+ *
+ * GitHubActionsCredential credential = new GitHubActionsCredentialBuilder().build();
+ *
+ *
+ *
+ * @see GitHubActionsCredentialBuilder
+ */
+@Immutable
+public class GitHubActionsCredential implements TokenCredential {
+ private static final ClientLogger LOGGER = new ClientLogger(GitHubActionsCredential.class);
+ private final IdentityClient identityClient;
+ private final IdentitySyncClient identitySyncClient;
+
+ GitHubActionsCredential(String clientId, String tenantId, String requestUrl, String requestToken,
+ IdentityClientOptions options) {
+ IdentityClientBuilder builder = new IdentityClientBuilder().clientId(clientId)
+ .tenantId(tenantId)
+ .identityClientOptions(options)
+ .clientAssertionSupplierWithHttpPipeline(pipeline -> {
+ HttpRequest request = new HttpRequest(HttpMethod.GET, requestUrl)
+ .setHeader(HttpHeaderName.AUTHORIZATION, "Bearer " + requestToken);
+ try (HttpResponse response = pipeline.sendSync(request, Context.NONE)) {
+ if (response.getStatusCode() != 200) {
+ throw authenticationError(
+ "GitHub OIDC request returned status code " + response.getStatusCode() + ".", response);
+ }
+ return readAssertion(response);
+ }
+ });
+ identityClient = builder.build();
+ identitySyncClient = builder.buildSyncClient();
+ }
+
+ /**
+ * Asynchronously acquires an access token, using the token cache when possible.
+ *
+ * @param request the scopes, tenant, and authentication options for the token request.
+ * @return a publisher containing the access token, or an authentication error.
+ */
+ @Override
+ public Mono getToken(TokenRequestContext request) {
+ // The confidential-client assertion callback performs synchronous HTTP I/O.
+ return Mono.defer(() -> identityClient.authenticateWithConfidentialClientCache(request)
+ .onErrorResume(Exception.class, error -> {
+ IdentityUtil.rethrowIfShutdownSignal(error);
+ return Mono.empty();
+ })
+ .switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request))))
+ .subscribeOn(Schedulers.boundedElastic())
+ .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request))
+ .doOnError(
+ error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error));
+ }
+
+ /**
+ * Synchronously acquires an access token, using the token cache when possible.
+ *
+ * @param request the scopes, tenant, and authentication options for the token request.
+ * @return the access token.
+ * @throws ClientAuthenticationException if the GitHub OIDC request fails or returns an invalid assertion response.
+ */
+ @Override
+ public AccessToken getTokenSync(TokenRequestContext request) {
+ try {
+ AccessToken token = identitySyncClient.authenticateWithConfidentialClientCache(request);
+ if (token != null) {
+ LoggingUtil.logTokenSuccess(LOGGER, request);
+ return token;
+ }
+ } catch (RuntimeException e) {
+ IdentityUtil.rethrowIfShutdownSignal(e);
+ }
+ try {
+ AccessToken token = identitySyncClient.authenticateWithConfidentialClient(request);
+ LoggingUtil.logTokenSuccess(LOGGER, request);
+ return token;
+ } catch (RuntimeException e) {
+ LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e);
+ IdentityUtil.rethrowIfShutdownSignal(e);
+ throw LOGGER.logExceptionAsError(e);
+ }
+ }
+
+ private static String readAssertion(HttpResponse response) {
+ try (JsonReader reader = JsonProviders.createReader(response.getBodyAsBinaryData().toString())) {
+ String assertion = reader.readObject(objectReader -> {
+ String value = null;
+ while (objectReader.nextToken() != JsonToken.END_OBJECT) {
+ String fieldName = objectReader.getFieldName();
+ objectReader.nextToken();
+ if ("value".equals(fieldName)) {
+ if (objectReader.currentToken() != JsonToken.STRING) {
+ throw authenticationError("GitHub OIDC response must contain a string 'value'.", response);
+ }
+ value = objectReader.getString();
+ } else {
+ objectReader.skipChildren();
+ }
+ }
+ return value;
+ });
+ if (CoreUtils.isNullOrEmpty(assertion) || reader.nextToken() != JsonToken.END_DOCUMENT) {
+ throw authenticationError("GitHub OIDC response must contain a nonempty string 'value'.", response);
+ }
+ return assertion;
+ } catch (IOException | IllegalStateException e) {
+ throw LOGGER.logExceptionAsError(new ClientAuthenticationException(
+ "GitHubActionsCredential authentication failed. Invalid GitHub OIDC response.", response,
+ sanitizedCause(e)));
+ }
+ }
+
+ // Parser and URI exception messages can contain secrets. Retain their type and stack trace, not their input.
+ static RuntimeException sanitizedCause(Exception exception) {
+ if (exception == null) {
+ return null;
+ }
+ RuntimeException sanitized
+ = new IllegalArgumentException(exception.getClass().getSimpleName() + " (input redacted)");
+ sanitized.setStackTrace(exception.getStackTrace());
+ return sanitized;
+ }
+
+ private static RuntimeException authenticationError(String message, HttpResponse response) {
+ return LOGGER.logExceptionAsError(
+ new ClientAuthenticationException("GitHubActionsCredential authentication failed. " + message, response));
+ }
+}
diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredentialBuilder.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredentialBuilder.java
new file mode 100644
index 0000000000000..64d1c326e7ea5
--- /dev/null
+++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredentialBuilder.java
@@ -0,0 +1,170 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.identity;
+
+import com.azure.core.util.Configuration;
+import com.azure.core.util.CoreUtils;
+import com.azure.core.util.UrlBuilder;
+import com.azure.core.util.logging.ClientLogger;
+import com.azure.identity.implementation.IdentityClientOptions;
+import com.azure.identity.implementation.util.ValidationUtil;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.Locale;
+
+/**
+ * Fluent builder for {@link GitHubActionsCredential}.
+ *
+ * Client and tenant IDs can be supplied explicitly or through {@code AZURE_CLIENT_ID} and
+ * {@code AZURE_TENANT_ID}. GitHub supplies {@code ACTIONS_ID_TOKEN_REQUEST_URL} and
+ * {@code ACTIONS_ID_TOKEN_REQUEST_TOKEN} to workflow steps with {@code permissions: id-token: write}.
+ *
+ *
+ *
+ * GitHubActionsCredential credential = new GitHubActionsCredentialBuilder().build();
+ *
+ *
+ *
+ * @see GitHubActionsCredential
+ */
+public class GitHubActionsCredentialBuilder extends AadCredentialBuilderBase {
+ private static final ClientLogger LOGGER = new ClientLogger(GitHubActionsCredentialBuilder.class);
+ private String authorityHost;
+
+ /**
+ * Creates a builder for a GitHub Actions credential.
+ */
+ public GitHubActionsCredentialBuilder() {
+ }
+
+ @Override
+ public GitHubActionsCredentialBuilder authorityHost(String authorityHost) {
+ super.authorityHost(authorityHost);
+ this.authorityHost = authorityHost;
+ return this;
+ }
+
+ /**
+ * Enables the persistent token cache with the specified options. Persistence is disabled by default.
+ *
+ * @param tokenCachePersistenceOptions the persistent token cache options.
+ * @return this builder.
+ */
+ public GitHubActionsCredentialBuilder
+ tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) {
+ identityClientOptions.setTokenCacheOptions(tokenCachePersistenceOptions);
+ return this;
+ }
+
+ /**
+ * Builds a credential using the configured values and the GitHub Actions environment.
+ *
+ * An explicit client ID, tenant ID, or authority host takes precedence over its environment variable.
+ * The default authority is Azure Public. The assertion audience is derived from the authority host.
+ *
+ * @return the configured credential.
+ * @throws CredentialUnavailableException if required configuration is missing, the GitHub request URL is
+ * invalid, or the authority host does not have a supported token-exchange audience.
+ * @throws IllegalArgumentException if the tenant ID is invalid.
+ */
+ public GitHubActionsCredential build() {
+ Configuration configuration = identityClientOptions.getConfiguration();
+ if (configuration == null) {
+ configuration = Configuration.getGlobalConfiguration();
+ }
+ String resolvedClientId = required("AZURE_CLIENT_ID",
+ CoreUtils.isNullOrEmpty(clientId) ? configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID) : clientId);
+ String resolvedTenantId = required("AZURE_TENANT_ID",
+ CoreUtils.isNullOrEmpty(tenantId) ? configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID) : tenantId);
+ ValidationUtil.validateTenantIdCharacterRange(resolvedTenantId, LOGGER);
+ String requestUrl = required("ACTIONS_ID_TOKEN_REQUEST_URL", configuration.get("ACTIONS_ID_TOKEN_REQUEST_URL"));
+ String requestToken
+ = required("ACTIONS_ID_TOKEN_REQUEST_TOKEN", configuration.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN"));
+ String resolvedAuthority = authorityHost == null
+ ? configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
+ : authorityHost;
+ String audience = audienceForAuthority(resolvedAuthority);
+ IdentityClientOptions options = identityClientOptions.clone().setAuthorityHost(resolvedAuthority);
+ return new GitHubActionsCredential(resolvedClientId, resolvedTenantId,
+ requestUrlWithAudience(requestUrl, audience), requestToken, options);
+ }
+
+ private static String required(String name, String value) {
+ if (CoreUtils.isNullOrEmpty(value)) {
+ throw LOGGER.logExceptionAsError(new CredentialUnavailableException("GitHubActionsCredential requires "
+ + name + ". Configure the Azure client and tenant IDs and run in a GitHub Actions workflow with "
+ + "'permissions: id-token: write'."));
+ }
+ return value;
+ }
+
+ private static String audienceForAuthority(String authority) {
+ try {
+ URI uri = new URI(authority);
+ if ("https".equalsIgnoreCase(uri.getScheme()) && uri.getHost() != null && uri.getUserInfo() == null) {
+ switch (uri.getHost().toLowerCase(Locale.ROOT)) {
+ case "login.microsoftonline.com":
+ return "api://AzureADTokenExchange";
+
+ case "login.chinacloudapi.cn":
+ return "api://AzureADTokenExchangeChina";
+
+ case "login.microsoftonline.us":
+ return "api://AzureADTokenExchangeUSGov";
+
+ case "login.sovcloud-identity.fr":
+ return "api://AzureADTokenExchangeFrance";
+
+ case "login.sovcloud-identity.de":
+ return "api://AzureADTokenExchangeGermany";
+
+ case "login.sovcloud-identity.sg":
+ return "api://AzureADTokenExchangeGovSG";
+
+ default:
+ break;
+ }
+ }
+ } catch (URISyntaxException e) {
+ throw unsupportedAuthority(e);
+ }
+ throw unsupportedAuthority(null);
+ }
+
+ private static RuntimeException unsupportedAuthority(Exception cause) {
+ return LOGGER.logExceptionAsError(new CredentialUnavailableException(
+ "GitHubActionsCredential does not support the configured authority host. "
+ + "Use an Azure Public, China, US Government, France Government, Germany Government, "
+ + "or Singapore Government authority.",
+ GitHubActionsCredential.sanitizedCause(cause)));
+ }
+
+ private static String requestUrlWithAudience(String requestUrl, String audience) {
+ try {
+ URI uri = new URI(requestUrl);
+ if (!"https".equalsIgnoreCase(uri.getScheme())
+ || uri.getHost() == null
+ || uri.getUserInfo() != null
+ || uri.getFragment() != null) {
+ throw invalidRequestUrl(null);
+ }
+ return UrlBuilder.parse(requestUrl)
+ .setQueryParameter("audience", URLEncoder.encode(audience, StandardCharsets.UTF_8.name()))
+ .toString();
+ } catch (URISyntaxException | IOException e) {
+ throw invalidRequestUrl(e);
+ }
+ }
+
+ private static RuntimeException invalidRequestUrl(Exception cause) {
+ return LOGGER.logExceptionAsError(new CredentialUnavailableException(
+ "GitHubActionsCredential requires ACTIONS_ID_TOKEN_REQUEST_URL to be an absolute HTTPS URL "
+ + "without user information or a fragment.",
+ GitHubActionsCredential.sanitizedCause(cause)));
+ }
+}
diff --git a/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java b/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java
index 3685fd3bc5f47..98bf2fea1b819 100644
--- a/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java
+++ b/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java
@@ -39,6 +39,8 @@
import com.azure.identity.DeviceCodeCredentialBuilder;
import com.azure.identity.EnvironmentCredential;
import com.azure.identity.EnvironmentCredentialBuilder;
+import com.azure.identity.GitHubActionsCredential;
+import com.azure.identity.GitHubActionsCredentialBuilder;
import com.azure.identity.IntelliJCredential;
import com.azure.identity.IntelliJCredentialBuilder;
import com.azure.identity.InteractiveBrowserCredential;
@@ -302,6 +304,26 @@ public void azurePipelinesCredentialCodeSnippets() {
// END: com.azure.identity.credential.azurepipelinescredential.construct
}
+ /**
+ * Code snippets for {@link GitHubActionsCredential}.
+ */
+ public void gitHubActionsCredentialCodeSnippets() {
+ // BEGIN: com.azure.identity.credential.githubactionscredential.construct
+ GitHubActionsCredential credential = new GitHubActionsCredentialBuilder().build();
+ // END: com.azure.identity.credential.githubactionscredential.construct
+
+ // BEGIN: readme-sample-github-actions-credential
+ TokenCredential gitHubCredential = new GitHubActionsCredentialBuilder().build();
+ // END: readme-sample-github-actions-credential
+
+ // BEGIN: readme-sample-github-actions-credential-explicit
+ TokenCredential explicitCredential = new GitHubActionsCredentialBuilder()
+ .tenantId("")
+ .clientId("")
+ .build();
+ // END: readme-sample-github-actions-credential-explicit
+ }
+
public void silentAuthenticationSnippets() {
// BEGIN: com.azure.identity.silentauthentication
String authenticationRecordPath = "path/to/authentication-record.json";
diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialBuilderTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialBuilderTest.java
new file mode 100644
index 0000000000000..c623ebf9b6042
--- /dev/null
+++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialBuilderTest.java
@@ -0,0 +1,160 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.identity;
+
+import com.azure.core.credential.TokenRequestContext;
+import com.azure.core.util.Configuration;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.Map;
+
+import static com.azure.identity.GitHubActionsCredentialTest.SCOPE;
+import static com.azure.identity.GitHubActionsCredentialTest.credentialBuilder;
+import static com.azure.identity.GitHubActionsCredentialTest.configuration;
+import static com.azure.identity.GitHubActionsCredentialTest.parseForm;
+import static com.azure.identity.GitHubActionsCredentialTest.settings;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class GitHubActionsCredentialBuilderTest {
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "AZURE_TENANT_ID",
+ "AZURE_CLIENT_ID",
+ "ACTIONS_ID_TOKEN_REQUEST_URL",
+ "ACTIONS_ID_TOKEN_REQUEST_TOKEN" })
+ void validatesEveryRequiredSettingBeforeHttp(String setting) {
+ for (String value : new String[] { null, "" }) {
+ Map values = settings();
+ values.put(setting, value);
+ GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient();
+ CredentialUnavailableException error = assertThrows(CredentialUnavailableException.class,
+ () -> credentialBuilder(http).configuration(configuration(values)).build());
+ assertTrue(error.getMessage().contains(setting));
+ assertTrue(error.getMessage().contains("id-token: write"));
+ assertFalse(error.getMessage().contains("runner-token-sentinel"));
+ assertEquals(0, http.oidcRequests.get());
+ }
+ }
+
+ @Test
+ void explicitIdsOverrideEnvironmentAndCredentialsSnapshotBuilderValues() {
+ GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient();
+ GitHubActionsCredentialBuilder builder
+ = credentialBuilder(http).clientId("explicit-client").tenantId("explicit-tenant");
+ GitHubActionsCredential first = builder.build();
+ GitHubActionsCredential second = builder.clientId("second-client").tenantId("second-tenant").build();
+ assertEquals(0, http.oidcRequests.get());
+ first.getTokenSync(new TokenRequestContext().addScopes(SCOPE));
+ assertEquals("explicit-client", http.tokenForms.get(0).get("client_id"));
+ assertTrue(http.lastTokenPath.contains("explicit-tenant"));
+ second.getTokenSync(new TokenRequestContext().addScopes(SCOPE));
+ assertEquals("second-client", http.tokenForms.get(1).get("client_id"));
+ assertTrue(http.lastTokenPath.contains("second-tenant"));
+ }
+
+ @Test
+ void disabledConfigurationDoesNotFallBackToTheEnvironment() {
+ assertThrows(CredentialUnavailableException.class,
+ () -> new GitHubActionsCredentialBuilder().configuration(Configuration.NONE).build());
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "login.microsoftonline.com,AzureADTokenExchange",
+ "login.chinacloudapi.cn,AzureADTokenExchangeChina",
+ "login.microsoftonline.us,AzureADTokenExchangeUSGov",
+ "login.sovcloud-identity.fr,AzureADTokenExchangeFrance",
+ "login.sovcloud-identity.de,AzureADTokenExchangeGermany",
+ "login.sovcloud-identity.sg,AzureADTokenExchangeGovSG",
+ "LOGIN.MICROSOFTONLINE.COM,AzureADTokenExchange" })
+ void derivesTheAudienceFromTheConfiguredAuthority(String host, String audience) {
+ GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient();
+ Map values = settings();
+ values.put("AZURE_AUTHORITY_HOST", "https://" + host + "/");
+ values.put("ACTIONS_ID_TOKEN_REQUEST_URL",
+ "https://github-oidc.test/token?encoded=a%2Fb&audience=old&audience=duplicate");
+ credentialBuilder(http).configuration(configuration(values))
+ .build()
+ .getTokenSync(new TokenRequestContext().addScopes(SCOPE));
+ String query = http.oidcRequest.getUrl().getQuery();
+ assertEquals("api://" + audience, parseForm(query).get("audience"));
+ assertEquals("a/b", parseForm(query).get("encoded"));
+ assertEquals(1, query.split("audience=", -1).length - 1);
+ assertTrue(query.contains("api%3A%2F%2F"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void explicitAuthorityWinsRegardlessOfConfigurationSetterOrder(boolean configurationFirst) {
+ GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient();
+ Map values = settings();
+ values.put("AZURE_AUTHORITY_HOST", AzureAuthorityHosts.AZURE_CHINA);
+ GitHubActionsCredentialBuilder builder = credentialBuilder(http);
+ if (configurationFirst) {
+ builder.configuration(configuration(values)).authorityHost(AzureAuthorityHosts.AZURE_GOVERNMENT);
+ } else {
+ builder.authorityHost(AzureAuthorityHosts.AZURE_GOVERNMENT).configuration(configuration(values));
+ }
+ builder.build().getTokenSync(new TokenRequestContext().addScopes(SCOPE));
+ assertEquals("api://AzureADTokenExchangeUSGov",
+ parseForm(http.oidcRequest.getUrl().getQuery()).get("audience"));
+ assertEquals("login.microsoftonline.us", http.tokenRequest.getUrl().getHost());
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "https://unsupported.test",
+ "https://login.microsoftonline.com.attacker.test",
+ "https://login.microsoftonline.de",
+ "https://user:secret@login.microsoftonline.com" })
+ void rejectsUnsupportedAuthorityHosts(String authority) {
+ assertThrows(CredentialUnavailableException.class,
+ () -> credentialBuilder(new GitHubActionsCredentialTest.FakeHttpClient()).authorityHost(authority).build());
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "not a URI",
+ "/relative",
+ "http://github-oidc.test/token",
+ "https:///token",
+ "https://user:secret@github-oidc.test/token",
+ "https://github-oidc.test/token#fragment" })
+ void rejectsInvalidRunnerUrls(String url) {
+ Map values = settings();
+ values.put("ACTIONS_ID_TOKEN_REQUEST_URL", url);
+ CredentialUnavailableException error = assertThrows(CredentialUnavailableException.class,
+ () -> credentialBuilder(new GitHubActionsCredentialTest.FakeHttpClient())
+ .configuration(configuration(values))
+ .build());
+ assertFalse(error.getMessage().contains("secret"));
+ }
+
+ @Test
+ void validatesEnvironmentTenantAndSupportsUrlsWithoutQueries() {
+ Map values = settings();
+ values.put("AZURE_TENANT_ID", "invalid/tenant");
+ assertThrows(IllegalArgumentException.class,
+ () -> credentialBuilder(new GitHubActionsCredentialTest.FakeHttpClient())
+ .configuration(configuration(values))
+ .build());
+ values.put("AZURE_TENANT_ID", "valid-tenant");
+ values.put("ACTIONS_ID_TOKEN_REQUEST_URL", "https://github-oidc.test/token");
+ GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient();
+ assertNotNull(credentialBuilder(http).configuration(configuration(values))
+ .build()
+ .getTokenSync(new TokenRequestContext().addScopes(SCOPE)));
+ assertEquals("api://AzureADTokenExchange", parseForm(http.oidcRequest.getUrl().getQuery()).get("audience"));
+ }
+}
diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java
new file mode 100644
index 0000000000000..0e5a4bb006d02
--- /dev/null
+++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java
@@ -0,0 +1,339 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.identity;
+
+import com.azure.core.credential.AccessToken;
+import com.azure.core.credential.TokenRequestContext;
+import com.azure.core.exception.ClientAuthenticationException;
+import com.azure.core.http.HttpClient;
+import com.azure.core.http.HttpHeaderName;
+import com.azure.core.http.HttpHeaders;
+import com.azure.core.http.HttpMethod;
+import com.azure.core.http.HttpPipelineBuilder;
+import com.azure.core.http.HttpRequest;
+import com.azure.core.http.HttpResponse;
+import com.azure.core.http.policy.AddHeadersPolicy;
+import com.azure.core.test.http.MockHttpResponse;
+import com.azure.core.test.utils.TestConfigurationSource;
+import com.azure.core.util.Configuration;
+import com.azure.core.util.Context;
+import com.azure.identity.util.TestUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import reactor.core.publisher.Mono;
+import reactor.core.scheduler.Schedulers;
+import reactor.test.StepVerifier;
+
+import java.io.UnsupportedEncodingException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.time.OffsetDateTime;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class GitHubActionsCredentialTest {
+ static final String CLIENT_ID = "00000000-0000-0000-0000-000000000002";
+ static final String TENANT_ID = "contoso.onmicrosoft.com";
+ static final String SCOPE = "https://management.azure.com/.default";
+ static final String ASSERTION = "eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjQxMDI0NDQ4MDB9.signature";
+ static final Duration TIMEOUT = Duration.ofSeconds(20);
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void exchangesAssertionAndUsesAccessTokenCache(boolean async) {
+ FakeHttpClient http = new FakeHttpClient();
+ GitHubActionsCredential credential = credentialBuilder(http).build();
+ TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE);
+ AccessToken token = getToken(credential, request, async);
+ assertNotNull(token);
+ assertEquals("access-token-1", token.getToken());
+ assertTrue(token.getExpiresAt().isAfter(OffsetDateTime.now()));
+ assertEquals(CLIENT_ID, http.tokenForms.get(0).get("client_id"));
+ assertEquals(ASSERTION, http.tokenForms.get(0).get("client_assertion"));
+ assertEquals("client_credentials", http.tokenForms.get(0).get("grant_type"));
+ assertEquals("urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
+ http.tokenForms.get(0).get("client_assertion_type"));
+ assertTrue(http.tokenForms.get(0).get("scope").contains("https://management.azure.com/"));
+ assertTrue(http.lastTokenPath.contains(TENANT_ID));
+ int assertionRequests = http.oidcRequests.get();
+ assertEquals(token.getToken(), getToken(credential, request, async).getToken());
+ assertEquals(assertionRequests, http.oidcRequests.get());
+ assertEquals(1, http.tokenForms.size());
+ assertEquals(http.oidcRequests.get(), http.closedResponses.get());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void refreshesAssertionWhenAccessTokenIsNearExpiry(boolean async) {
+ FakeHttpClient http = new FakeHttpClient();
+ http.expiresIn = 60;
+ GitHubActionsCredential credential = credentialBuilder(http).build();
+ TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE);
+ getToken(credential, request, async);
+ int assertionRequests = http.oidcRequests.get();
+ assertEquals("access-token-2", getToken(credential, request, async).getToken());
+ assertTrue(http.oidcRequests.get() > assertionRequests);
+ assertEquals(2, http.tokenForms.size());
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = { 204, 400, 401 })
+ void rejectsHttpFailuresWithoutDisclosingResponse(int status) {
+ FakeHttpClient http = new FakeHttpClient();
+ http.oidcStatus = status;
+ http.oidcBody = "{\"value\":\"response-secret-sentinel\"}";
+ ClientAuthenticationException error = assertThrows(ClientAuthenticationException.class,
+ () -> credentialBuilder(http).build().getTokenSync(new TokenRequestContext().addScopes(SCOPE)));
+ assertTrue(error.getMessage().contains(Integer.toString(status)));
+ assertFalse(error.getMessage().contains("response-secret-sentinel"));
+ assertNull(error.getCause());
+ assertEquals(0, http.tokenForms.size());
+ assertEquals(http.oidcRequests.get(), http.closedResponses.get());
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "",
+ "null",
+ "[]",
+ "{}",
+ "{\"value\":null}",
+ "{\"value\":42}",
+ "{\"value\":true}",
+ "{\"value\":{}}",
+ "{\"value\":[]}",
+ "{\"value\":\"\"}",
+ "response-secret-sentinel",
+ "{\"value\":\"response-secret-sentinel\"",
+ "{\"value\":\"response-secret-sentinel\"} trailing" })
+ void rejectsInvalidResponsesWithoutDisclosingAssertions(String body) {
+ FakeHttpClient http = new FakeHttpClient();
+ http.oidcBody = body;
+ ClientAuthenticationException error = assertThrows(ClientAuthenticationException.class,
+ () -> credentialBuilder(http).build().getTokenSync(new TokenRequestContext().addScopes(SCOPE)));
+ assertFalse(error.getMessage().contains("response-secret-sentinel"));
+ StringWriter diagnostics = new StringWriter();
+ error.printStackTrace(new PrintWriter(diagnostics));
+ assertFalse(diagnostics.toString().contains("response-secret-sentinel"));
+ assertEquals(0, http.tokenForms.size());
+ assertEquals(http.oidcRequests.get(), http.closedResponses.get());
+ }
+
+ @Test
+ void asyncHttpFailureRetainsAuthenticationException() {
+ FakeHttpClient http = new FakeHttpClient();
+ http.oidcStatus = 401;
+ StepVerifier.create(credentialBuilder(http).build().getToken(new TokenRequestContext().addScopes(SCOPE)))
+ .expectError(ClientAuthenticationException.class)
+ .verify(TIMEOUT);
+ assertEquals(0, http.tokenForms.size());
+ }
+
+ @Test
+ void asyncRequestIsLazyAndDoesNotPerformHttpOnAnEventLoop() {
+ FakeHttpClient http = new FakeHttpClient();
+ GitHubActionsCredential credential = credentialBuilder(http).build();
+ Mono token = credential.getToken(new TokenRequestContext().addScopes(SCOPE));
+ assertEquals(0, http.oidcRequests.get());
+ StepVerifier.create(token.subscribeOn(Schedulers.parallel()))
+ .assertNext(value -> assertEquals("access-token-1", value.getToken()))
+ .expectComplete()
+ .verify(TIMEOUT);
+ assertFalse(http.nonBlockingOidcThread.get());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void propagatesTransportAndEntraFailures(boolean async) {
+ FakeHttpClient http = new FakeHttpClient();
+ http.transportFailure = new IllegalStateException("GitHub transport unavailable");
+ RuntimeException transportError = assertThrows(RuntimeException.class,
+ () -> getToken(credentialBuilder(http).build(), new TokenRequestContext().addScopes(SCOPE), async));
+ Throwable cause = transportError;
+ while (cause.getCause() != null) {
+ cause = cause.getCause();
+ }
+ assertSame(http.transportFailure, cause);
+ assertEquals(0, http.tokenForms.size());
+
+ http.transportFailure = null;
+ http.tokenStatus = 400;
+ RuntimeException tokenError = assertThrows(RuntimeException.class,
+ () -> getToken(credentialBuilder(http).build(), new TokenRequestContext().addScopes(SCOPE), async));
+ assertTrue(tokenError.getMessage().contains("bad-federation"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void forwardsTenantAndCaeOptions(boolean async) {
+ FakeHttpClient http = new FakeHttpClient();
+ GitHubActionsCredential credential
+ = credentialBuilder(http).additionallyAllowedTenants("other.contoso.com").build();
+ TokenRequestContext request
+ = new TokenRequestContext().addScopes(SCOPE).setTenantId("other.contoso.com").setCaeEnabled(true);
+ getToken(credential, request, async);
+ assertTrue(http.lastTokenPath.contains("other.contoso.com"));
+ String claims = http.tokenForms.get(0).get("claims");
+ assertNotNull(claims);
+ assertTrue(claims.contains("CP1"), claims);
+ }
+
+ @Test
+ void forwardsClaimsOnAsyncTokenRequests() {
+ FakeHttpClient http = new FakeHttpClient();
+ TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE)
+ .setCaeEnabled(true)
+ .setClaims("{\"access_token\":{\"auth_time\":{\"essential\":true}}}");
+ getToken(credentialBuilder(http).build(), request, true);
+ assertTrue(http.tokenForms.get(0).get("claims").contains("auth_time"));
+ }
+
+ @Test
+ void usesTheSuppliedPipelineForBothRequests() {
+ FakeHttpClient http = new FakeHttpClient();
+ HttpHeaderName header = HttpHeaderName.fromString("x-test-credential");
+ GitHubActionsCredential credential = credentialBuilder(http).pipeline(new HttpPipelineBuilder().httpClient(http)
+ .policies(new AddHeadersPolicy(new HttpHeaders().set(header, "custom-pipeline")))
+ .build()).build();
+ credential.getTokenSync(new TokenRequestContext().addScopes(SCOPE));
+ assertEquals("custom-pipeline", http.oidcRequest.getHeaders().getValue(header));
+ assertEquals("custom-pipeline", http.tokenRequest.getHeaders().getValue(header));
+ }
+
+ static GitHubActionsCredentialBuilder credentialBuilder(FakeHttpClient http) {
+ return new GitHubActionsCredentialBuilder().configuration(configuration(settings()))
+ .httpClient(http)
+ .disableInstanceDiscovery();
+ }
+
+ static Map settings() {
+ Map settings = new HashMap<>();
+ settings.put("AZURE_CLIENT_ID", CLIENT_ID);
+ settings.put("AZURE_TENANT_ID", TENANT_ID);
+ settings.put("ACTIONS_ID_TOKEN_REQUEST_URL", "https://github-oidc.test/token?api-version=1");
+ settings.put("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "runner-token-sentinel");
+ return settings;
+ }
+
+ static Configuration configuration(Map settings) {
+ TestConfigurationSource source = new TestConfigurationSource();
+ settings.forEach(source::put);
+ return TestUtils.createTestConfiguration(source);
+ }
+
+ private static AccessToken getToken(GitHubActionsCredential credential, TokenRequestContext request,
+ boolean async) {
+ return async ? credential.getToken(request).block(TIMEOUT) : credential.getTokenSync(request);
+ }
+
+ static Map parseForm(String body) {
+ Map result = new HashMap<>();
+ for (String parameter : body.split("&")) {
+ String[] parts = parameter.split("=", 2);
+ try {
+ result.put(URLDecoder.decode(parts[0], StandardCharsets.UTF_8.name()),
+ parts.length == 1 ? "" : URLDecoder.decode(parts[1], StandardCharsets.UTF_8.name()));
+ } catch (UnsupportedEncodingException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+ return result;
+ }
+
+ static class FakeHttpClient implements HttpClient {
+ final AtomicInteger oidcRequests = new AtomicInteger();
+ final AtomicInteger closedResponses = new AtomicInteger();
+ final AtomicBoolean nonBlockingOidcThread = new AtomicBoolean();
+ final List
*
* @return the configured credential.
* @throws CredentialUnavailableException if required configuration is missing, the GitHub request URL is
@@ -90,9 +93,26 @@ public GitHubActionsCredential build() {
? configuration.get("AZURE_TENANT_ID")
: confidentialClientOptions.getTenantId());
ValidationUtil.validateTenantIdCharacterRange(tenantId, LOGGER);
- String requestUrl = required("ACTIONS_ID_TOKEN_REQUEST_URL", configuration.get("ACTIONS_ID_TOKEN_REQUEST_URL"));
- String requestToken
- = required("ACTIONS_ID_TOKEN_REQUEST_TOKEN", configuration.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN"));
+ String requestUrl = configuration.get("ACTIONS_ID_TOKEN_REQUEST_URL");
+ String requestToken = configuration.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN");
+ List missing = new ArrayList<>(2);
+ if (CoreUtils.isNullOrEmpty(requestUrl)) {
+ missing.add("ACTIONS_ID_TOKEN_REQUEST_URL");
+ }
+ if (CoreUtils.isNullOrEmpty(requestToken)) {
+ missing.add("ACTIONS_ID_TOKEN_REQUEST_TOKEN");
+ }
+ if (!missing.isEmpty()) {
+ String missingSettings = String.join(", ", missing);
+ String message
+ = "GitHubActionsCredential requires " + missingSettings + ". Run in a GitHub Actions workflow with "
+ + "'permissions: id-token: write'. For troubleshooting information, see "
+ + "https://aka.ms/azsdk/java/identity/troubleshoot.";
+ throw LOGGER.throwableAtError()
+ .addKeyValue("setting", missingSettings)
+ .log("GitHubActionsCredential configuration is incomplete.",
+ ignored -> new CredentialUnavailableException(message));
+ }
String resolvedAuthority = authorityHost == null ? configuration.get("AZURE_AUTHORITY_HOST") : authorityHost;
if (resolvedAuthority == null) {
resolvedAuthority = AzureAuthorityHosts.AZURE_PUBLIC_CLOUD;
diff --git a/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialBuilderTest.java b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialBuilderTest.java
index 8e4f5667aac85..17c9062c22740 100644
--- a/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialBuilderTest.java
+++ b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialBuilderTest.java
@@ -42,10 +42,31 @@ void validatesEveryRequiredSettingBeforeHttp(String setting) {
assertTrue(error.getMessage().contains(setting));
assertTrue(error.getMessage().contains("id-token: write"));
assertFalse(error.getMessage().contains("runner-token-sentinel"));
+ if (setting.startsWith("ACTIONS_ID_TOKEN_REQUEST_")) {
+ assertTrue(error.getMessage().contains("https://aka.ms/azsdk/java/identity/troubleshoot"));
+ String configuredSetting
+ = setting.endsWith("_URL") ? "ACTIONS_ID_TOKEN_REQUEST_TOKEN" : "ACTIONS_ID_TOKEN_REQUEST_URL";
+ assertFalse(error.getMessage().contains(configuredSetting));
+ }
assertEquals(0, http.oidcRequests.get());
}
}
+ @ParameterizedTest
+ @CsvSource(value = { "null,null", "null,''", "'',null", "'',''" }, nullValues = "null")
+ void reportsBothMissingGitHubVariables(String requestUrl, String requestToken) {
+ Map values = settings();
+ values.put("ACTIONS_ID_TOKEN_REQUEST_URL", requestUrl);
+ values.put("ACTIONS_ID_TOKEN_REQUEST_TOKEN", requestToken);
+ GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient();
+ CredentialUnavailableException error = assertThrows(CredentialUnavailableException.class,
+ () -> credentialBuilder(http).configuration(configuration(values)).build());
+ assertTrue(error.getMessage().contains("ACTIONS_ID_TOKEN_REQUEST_URL, ACTIONS_ID_TOKEN_REQUEST_TOKEN"));
+ assertTrue(error.getMessage().contains("permissions: id-token: write"));
+ assertTrue(error.getMessage().contains("https://aka.ms/azsdk/java/identity/troubleshoot"));
+ assertEquals(0, http.oidcRequests.get());
+ }
+
@Test
void explicitIdsOverrideEnvironmentAndCredentialsSnapshotBuilderValues() {
GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient();
diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredentialBuilder.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredentialBuilder.java
index 64d1c326e7ea5..23d9e1d6da579 100644
--- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredentialBuilder.java
+++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredentialBuilder.java
@@ -15,6 +15,8 @@
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Locale;
/**
@@ -65,7 +67,8 @@ public GitHubActionsCredentialBuilder authorityHost(String authorityHost) {
* Builds a credential using the configured values and the GitHub Actions environment.
*
* An explicit client ID, tenant ID, or authority host takes precedence over its environment variable.
- * The default authority is Azure Public. The assertion audience is derived from the authority host.
+ * The default authority is Azure Public. The assertion audience is derived from the authority host.
+ * Missing GitHub runner variables are reported together with a link to troubleshooting guidance.
*
* @return the configured credential.
* @throws CredentialUnavailableException if required configuration is missing, the GitHub request URL is
@@ -82,9 +85,21 @@ public GitHubActionsCredential build() {
String resolvedTenantId = required("AZURE_TENANT_ID",
CoreUtils.isNullOrEmpty(tenantId) ? configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID) : tenantId);
ValidationUtil.validateTenantIdCharacterRange(resolvedTenantId, LOGGER);
- String requestUrl = required("ACTIONS_ID_TOKEN_REQUEST_URL", configuration.get("ACTIONS_ID_TOKEN_REQUEST_URL"));
- String requestToken
- = required("ACTIONS_ID_TOKEN_REQUEST_TOKEN", configuration.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN"));
+ String requestUrl = configuration.get("ACTIONS_ID_TOKEN_REQUEST_URL");
+ String requestToken = configuration.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN");
+ List missing = new ArrayList<>(2);
+ if (CoreUtils.isNullOrEmpty(requestUrl)) {
+ missing.add("ACTIONS_ID_TOKEN_REQUEST_URL");
+ }
+ if (CoreUtils.isNullOrEmpty(requestToken)) {
+ missing.add("ACTIONS_ID_TOKEN_REQUEST_TOKEN");
+ }
+ if (!missing.isEmpty()) {
+ throw LOGGER.logExceptionAsError(new CredentialUnavailableException("GitHubActionsCredential requires "
+ + String.join(", ", missing) + ". Run in a GitHub Actions workflow with "
+ + "'permissions: id-token: write'. For troubleshooting information, see "
+ + "https://aka.ms/azsdk/java/identity/troubleshoot."));
+ }
String resolvedAuthority = authorityHost == null
? configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
: authorityHost;
diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialBuilderTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialBuilderTest.java
index c623ebf9b6042..98c150dee6e21 100644
--- a/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialBuilderTest.java
+++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialBuilderTest.java
@@ -41,10 +41,31 @@ void validatesEveryRequiredSettingBeforeHttp(String setting) {
assertTrue(error.getMessage().contains(setting));
assertTrue(error.getMessage().contains("id-token: write"));
assertFalse(error.getMessage().contains("runner-token-sentinel"));
+ if (setting.startsWith("ACTIONS_ID_TOKEN_REQUEST_")) {
+ assertTrue(error.getMessage().contains("https://aka.ms/azsdk/java/identity/troubleshoot"));
+ String configuredSetting
+ = setting.endsWith("_URL") ? "ACTIONS_ID_TOKEN_REQUEST_TOKEN" : "ACTIONS_ID_TOKEN_REQUEST_URL";
+ assertFalse(error.getMessage().contains(configuredSetting));
+ }
assertEquals(0, http.oidcRequests.get());
}
}
+ @ParameterizedTest
+ @CsvSource(value = { "null,null", "null,''", "'',null", "'',''" }, nullValues = "null")
+ void reportsBothMissingGitHubVariables(String requestUrl, String requestToken) {
+ Map values = settings();
+ values.put("ACTIONS_ID_TOKEN_REQUEST_URL", requestUrl);
+ values.put("ACTIONS_ID_TOKEN_REQUEST_TOKEN", requestToken);
+ GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient();
+ CredentialUnavailableException error = assertThrows(CredentialUnavailableException.class,
+ () -> credentialBuilder(http).configuration(configuration(values)).build());
+ assertTrue(error.getMessage().contains("ACTIONS_ID_TOKEN_REQUEST_URL, ACTIONS_ID_TOKEN_REQUEST_TOKEN"));
+ assertTrue(error.getMessage().contains("permissions: id-token: write"));
+ assertTrue(error.getMessage().contains("https://aka.ms/azsdk/java/identity/troubleshoot"));
+ assertEquals(0, http.oidcRequests.get());
+ }
+
@Test
void explicitIdsOverrideEnvironmentAndCredentialsSnapshotBuilderValues() {
GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient();
From 51e6b0e94508c10ad19299999e7b51038a5486d5 Mon Sep 17 00:00:00 2001
From: Victor Colin Amador
Date: Thu, 22 Oct 2026 03:22:29 -0700
Subject: [PATCH 05/11] Updated CSpell files
---
sdk/identity-v2/cspell.yml | 1 +
sdk/identity/cspell.yml | 1 +
2 files changed, 2 insertions(+)
diff --git a/sdk/identity-v2/cspell.yml b/sdk/identity-v2/cspell.yml
index 47699c91f6e88..fd57e4f94e7e3 100644
--- a/sdk/identity-v2/cspell.yml
+++ b/sdk/identity-v2/cspell.yml
@@ -8,3 +8,4 @@ import:
- ../../.vscode/cspell.json
words:
- "toolsl"
+ - "sovcloud"
diff --git a/sdk/identity/cspell.yml b/sdk/identity/cspell.yml
index 7a4a6dc172f24..f1799a81359ca 100644
--- a/sdk/identity/cspell.yml
+++ b/sdk/identity/cspell.yml
@@ -20,3 +20,4 @@ words:
- "maanged"
- "obocredential"
- "psql"
+ - "sovcloud"
From b05b5dfbba76b5fb8040a3c2e174a5a48fea4545 Mon Sep 17 00:00:00 2001
From: Victor Colin Amador
Date: Thu, 22 Oct 2026 04:15:46 -0700
Subject: [PATCH 06/11] Relocated snippet ffiles for AZure Identity V2
---
sdk/identity-v2/azure-identity/pom.xml | 8 --------
.../GitHubActionsCredentialJavaDocCodeSnippets.java | 0
2 files changed, 8 deletions(-)
rename sdk/identity-v2/azure-identity/src/{test => samples}/java/com/azure/v2/identity/GitHubActionsCredentialJavaDocCodeSnippets.java (100%)
diff --git a/sdk/identity-v2/azure-identity/pom.xml b/sdk/identity-v2/azure-identity/pom.xml
index 3e27aac5dfaea..11a21be3446c2 100644
--- a/sdk/identity-v2/azure-identity/pom.xml
+++ b/sdk/identity-v2/azure-identity/pom.xml
@@ -117,14 +117,6 @@
-
- com.azure.tools
- codesnippet-maven-plugin
-
- ${project.basedir}/src/test/java
- **/*CodeSnippets.java
-
-
org.apache.maven.plugins
maven-enforcer-plugin
diff --git a/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialJavaDocCodeSnippets.java b/sdk/identity-v2/azure-identity/src/samples/java/com/azure/v2/identity/GitHubActionsCredentialJavaDocCodeSnippets.java
similarity index 100%
rename from sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialJavaDocCodeSnippets.java
rename to sdk/identity-v2/azure-identity/src/samples/java/com/azure/v2/identity/GitHubActionsCredentialJavaDocCodeSnippets.java
From 7691857f756cf6e7f20dd73701b6f84c540125fa Mon Sep 17 00:00:00 2001
From: Victor Colin Amador
Date: Thu, 22 Oct 2026 21:29:42 -0700
Subject: [PATCH 07/11] Fix GitHub Actions credential retries and CAE handling
---
sdk/identity-v2/azure-identity/CHANGELOG.md | 1 +
.../v2/identity/GitHubActionsCredential.java | 3 ++
.../client/ConfidentialClient.java | 7 +++
.../identity/GitHubActionsCredentialTest.java | 20 ++++++++
sdk/identity/azure-identity/CHANGELOG.md | 2 +
.../identity/GitHubActionsCredential.java | 6 +++
.../implementation/IdentityClient.java | 5 +-
.../implementation/IdentityClientBase.java | 3 +-
.../implementation/IdentitySyncClient.java | 13 ++---
.../identity/GitHubActionsCredentialTest.java | 47 +++++++++++++++++++
10 files changed, 99 insertions(+), 8 deletions(-)
diff --git a/sdk/identity-v2/azure-identity/CHANGELOG.md b/sdk/identity-v2/azure-identity/CHANGELOG.md
index 435e8e3733e87..ddba9fe06e1c9 100644
--- a/sdk/identity-v2/azure-identity/CHANGELOG.md
+++ b/sdk/identity-v2/azure-identity/CHANGELOG.md
@@ -11,6 +11,7 @@
### Bugs Fixed
+- Fixed client-credentials authentication to acquire a new token when handling a Continuous Access Evaluation (CAE) claims challenge.
- Fixed `DefaultAzureCredential` failing after a credential successfully acquired a token.
- Aligned user-assigned managed identity validation for Azure Service Fabric with `azure-identity`.
diff --git a/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredential.java b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredential.java
index 347c5d97aa0c0..ce710562f8c9c 100644
--- a/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredential.java
+++ b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredential.java
@@ -65,6 +65,9 @@ public class GitHubActionsCredential implements TokenCredential {
/**
* Acquires an access token, using the token cache when possible.
*
+ * Requests with a Continuous Access Evaluation (CAE) claims challenge acquire a new token instead of reusing a
+ * cached token.
+ *
* @param request the scopes, tenant, and authentication options for the token request.
* @return the access token.
* @throws CredentialAuthenticationException if the GitHub OIDC request fails or returns an invalid assertion response.
diff --git a/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/implementation/client/ConfidentialClient.java b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/implementation/client/ConfidentialClient.java
index 04ad98a803dbf..6bd495389cb0b 100644
--- a/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/implementation/client/ConfidentialClient.java
+++ b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/implementation/client/ConfidentialClient.java
@@ -89,6 +89,10 @@ public AccessToken authenticate(TokenRequestContext request) {
builder.clientCredential(ClientCredentialFactory.createFromClientAssertion(
confidentialClientOptions.getClientAssertionFunction().apply(getPipeline())));
}
+ if (request.isCaeEnabled() && request.getClaims() != null) {
+ ClaimsRequest claimsRequest = ClaimsRequest.formatAsClaimsRequest(request.getClaims());
+ builder.claims(claimsRequest).skipCache(true);
+ }
try {
return new MsalToken(confidentialClient.acquireToken(builder.build()).get());
} catch (InterruptedException | ExecutionException e) {
@@ -116,6 +120,9 @@ public AccessToken authenticateWithCache(TokenRequestContext request) {
*/
@SuppressWarnings("deprecation")
public AccessToken authenticateWithCache(TokenRequestContext request, IAccount account) {
+ if (account == null && request.isCaeEnabled() && request.getClaims() != null) {
+ return null;
+ }
ConfidentialClientApplication confidentialClientApplication = getConfidentialClientInstance(request).getValue();
SilentParameters.SilentParametersBuilder parametersBuilder
= SilentParameters.builder(new HashSet<>(request.getScopes()))
diff --git a/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialTest.java b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialTest.java
index bbd0bec149fb1..dd11442a77eb7 100644
--- a/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialTest.java
+++ b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialTest.java
@@ -156,6 +156,26 @@ void forwardsTenantAndCaeOptions() {
assertTrue(claims.contains("CP1"), claims);
}
+ @Test
+ void refreshesCachedTokenForCaeClaims() {
+ FakeHttpClient http = new FakeHttpClient();
+ GitHubActionsCredential credential = credentialBuilder(http).build();
+ TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE).setCaeEnabled(true);
+ assertEquals("access-token-1", credential.getToken(request).getToken());
+ assertEquals("access-token-1", credential.getToken(request).getToken());
+ assertEquals(1, http.tokenForms.size());
+
+ TokenRequestContext claimsRequest = new TokenRequestContext().addScopes(SCOPE)
+ .setCaeEnabled(true)
+ .setClaims("{\"access_token\":{\"auth_time\":{\"essential\":true}}}");
+ assertEquals("access-token-2", credential.getToken(claimsRequest).getToken());
+ assertEquals(2, http.tokenForms.size());
+ String claims = http.tokenForms.get(1).get("claims");
+ assertNotNull(claims);
+ assertTrue(claims.contains("auth_time"), claims);
+ assertTrue(claims.contains("CP1"), claims);
+ }
+
static GitHubActionsCredentialBuilder credentialBuilder(FakeHttpClient http) {
return new GitHubActionsCredentialBuilder().configuration(configuration(settings()))
.httpClient(http)
diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md
index e842901ffe19c..1723ceae1e02d 100644
--- a/sdk/identity/azure-identity/CHANGELOG.md
+++ b/sdk/identity/azure-identity/CHANGELOG.md
@@ -11,6 +11,8 @@
### Bugs Fixed
+- Fixed an initial OIDC request failure preventing later authentication attempts with the same `AzurePipelinesCredential` or `GitHubActionsCredential` instance.
+- Fixed client-credentials authentication to acquire a new token when handling a Continuous Access Evaluation (CAE) claims challenge.
- Disabled MSAL's internal retry for Confidential Client, Managed Identity and Public Client Applications. ([#48472](https://github.com/Azure/azure-sdk-for-java/pull/48472))
- Fixed misleading authentication error reporting when token requests are interrupted or the JVM shuts down. ([#50585](https://github.com/Azure/azure-sdk-for-java/issues/50585))
- Fixed IMDS discovery in `DefaultAzureCredential` to wait for HTTP response headers with a read timeout, allowing the credential chain to continue when a local endpoint accepts connections but does not respond, while preserving fallback on probe setup failures. ([#50517](https://github.com/Azure/azure-sdk-for-java/pull/50517))
diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java
index 13aa8dd6d6bea..2d603ec48b35f 100644
--- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java
+++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java
@@ -78,6 +78,9 @@ public class GitHubActionsCredential implements TokenCredential {
/**
* Asynchronously acquires an access token, using the token cache when possible.
*
+ * GitHub OIDC failures can be retried without rebuilding the credential. Requests with a Continuous Access
+ * Evaluation (CAE) claims challenge acquire a new token instead of reusing a cached token.
+ *
* @param request the scopes, tenant, and authentication options for the token request.
* @return a publisher containing the access token, or an authentication error.
*/
@@ -99,6 +102,9 @@ public Mono getToken(TokenRequestContext request) {
/**
* Synchronously acquires an access token, using the token cache when possible.
*
+ * Requests with a Continuous Access Evaluation (CAE) claims challenge acquire a new token instead of reusing a
+ * cached token.
+ *
* @param request the scopes, tenant, and authentication options for the token request.
* @return the access token.
* @throws ClientAuthenticationException if the GitHub OIDC request fails or returns an invalid assertion response.
diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClient.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClient.java
index 229d5b5bd78a3..e95c8335910e4 100644
--- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClient.java
+++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClient.java
@@ -555,7 +555,7 @@ public Mono authenticateWithConfidentialClient(TokenRequestContext
if (request.isCaeEnabled() && request.getClaims() != null) {
ClaimsRequest claimsRequest = ClaimsRequest.formatAsClaimsRequest(request.getClaims());
- builder.claims(claimsRequest);
+ builder.claims(claimsRequest).skipCache(true);
}
return builder;
}
@@ -706,6 +706,9 @@ public Mono authenticateWithConfidentialClientCache(TokenRequestCon
*/
@SuppressWarnings("deprecation")
public Mono authenticateWithConfidentialClientCache(TokenRequestContext request, IAccount account) {
+ if (account == null && request.isCaeEnabled() && request.getClaims() != null) {
+ return Mono.empty();
+ }
return getConfidentialClientInstance(request).getValue().flatMap(confidentialClient -> Mono.fromFuture(() -> {
SilentParameters.SilentParametersBuilder parametersBuilder
= SilentParameters.builder(new HashSet<>(request.getScopes()))
diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClientBase.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClientBase.java
index 704348b3ce41d..168efacc7da76 100644
--- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClientBase.java
+++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClientBase.java
@@ -225,8 +225,9 @@ ConfidentialClientApplication getConfidentialClient(boolean enableCae) {
} else if (clientAssertionSupplier != null) {
credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get());
} else if (clientAssertionSupplierWithHttpPipeline != null) {
+ // Fetch remote assertions during token acquisition, not permanently cached client initialization.
credential = ClientCredentialFactory
- .createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(getPipeline()));
+ .createFromCallback(() -> clientAssertionSupplierWithHttpPipeline.apply(getPipeline()));
} else {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("Must provide client secret or client certificate path."
diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentitySyncClient.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentitySyncClient.java
index 313f8a1fdd016..2befa7e935525 100644
--- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentitySyncClient.java
+++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentitySyncClient.java
@@ -134,6 +134,10 @@ public AccessToken authenticateWithConfidentialClient(TokenRequestContext reques
builder.clientCredential(ClientCredentialFactory
.createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(getPipeline())));
}
+ if (request.isCaeEnabled() && request.getClaims() != null) {
+ ClaimsRequest claimsRequest = ClaimsRequest.formatAsClaimsRequest(request.getClaims());
+ builder.claims(claimsRequest).skipCache(true);
+ }
try {
return new MsalToken(awaitTokenResult(confidentialClient.acquireToken(builder.build())));
} catch (ExecutionException e) {
@@ -160,17 +164,14 @@ private SynchronousAccessor getPublicClientInstance(Tok
*/
@SuppressWarnings("deprecation")
public AccessToken authenticateWithConfidentialClientCache(TokenRequestContext request) {
+ if (request.isCaeEnabled() && request.getClaims() != null) {
+ return null;
+ }
ConfidentialClientApplication confidentialClientApplication = getConfidentialClientInstance(request).getValue();
SilentParameters.SilentParametersBuilder parametersBuilder
= SilentParameters.builder(new HashSet<>(request.getScopes()))
.tenant(IdentityUtil.resolveTenantId(tenantId, request, options));
- if (request.isCaeEnabled() && request.getClaims() != null) {
- ClaimsRequest claimsRequest = ClaimsRequest.formatAsClaimsRequest(request.getClaims());
- parametersBuilder.claims(claimsRequest);
- parametersBuilder.forceRefresh(true);
- }
-
try {
IAuthenticationResult authenticationResult
= awaitTokenResult(confidentialClientApplication.acquireTokenSilently(parametersBuilder.build()));
diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java
index 0e5a4bb006d02..a80988c0cfd3e 100644
--- a/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java
+++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java
@@ -148,6 +148,32 @@ void asyncHttpFailureRetainsAuthenticationException() {
assertEquals(0, http.tokenForms.size());
}
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void retriesAsyncAuthenticationAfterOidcFailure(boolean caeEnabled) {
+ FakeHttpClient http = new FakeHttpClient();
+ http.oidcStatus = 401;
+ GitHubActionsCredential credential = credentialBuilder(http).build();
+ TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE).setCaeEnabled(caeEnabled);
+ Mono token = credential.getToken(request);
+ StepVerifier.create(token).expectError(ClientAuthenticationException.class).verify(TIMEOUT);
+ int failedRequests = http.oidcRequests.get();
+ assertTrue(failedRequests > 0);
+ assertEquals(0, http.tokenForms.size());
+
+ http.oidcStatus = 200;
+ StepVerifier.create(token)
+ .assertNext(value -> assertEquals("access-token-1", value.getToken()))
+ .expectComplete()
+ .verify(TIMEOUT);
+ int successfulRequests = http.oidcRequests.get();
+ assertTrue(successfulRequests > failedRequests);
+ assertEquals("access-token-1", getToken(credential, request, true).getToken());
+ assertEquals(successfulRequests, http.oidcRequests.get());
+ assertEquals(1, http.tokenForms.size());
+ assertEquals(http.oidcRequests.get(), http.closedResponses.get());
+ }
+
@Test
void asyncRequestIsLazyAndDoesNotPerformHttpOnAnEventLoop() {
FakeHttpClient http = new FakeHttpClient();
@@ -207,6 +233,27 @@ void forwardsClaimsOnAsyncTokenRequests() {
assertTrue(http.tokenForms.get(0).get("claims").contains("auth_time"));
}
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void refreshesCachedTokenForCaeClaims(boolean async) {
+ FakeHttpClient http = new FakeHttpClient();
+ GitHubActionsCredential credential = credentialBuilder(http).build();
+ TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE).setCaeEnabled(true);
+ assertEquals("access-token-1", getToken(credential, request, async).getToken());
+ assertEquals("access-token-1", getToken(credential, request, async).getToken());
+ assertEquals(1, http.tokenForms.size());
+
+ TokenRequestContext claimsRequest = new TokenRequestContext().addScopes(SCOPE)
+ .setCaeEnabled(true)
+ .setClaims("{\"access_token\":{\"auth_time\":{\"essential\":true}}}");
+ assertEquals("access-token-2", getToken(credential, claimsRequest, async).getToken());
+ assertEquals(2, http.tokenForms.size());
+ String claims = http.tokenForms.get(1).get("claims");
+ assertNotNull(claims);
+ assertTrue(claims.contains("auth_time"), claims);
+ assertTrue(claims.contains("CP1"), claims);
+ }
+
@Test
void usesTheSuppliedPipelineForBothRequests() {
FakeHttpClient http = new FakeHttpClient();
From e173b3851703ba2d59e4bb5bc36a981a0e5adbfc Mon Sep 17 00:00:00 2001
From: Victor Colin Amador
Date: Mon, 2 Nov 2026 15:12:33 -0800
Subject: [PATCH 08/11] Align GitHub Actions credential error messages
---
sdk/identity-v2/azure-identity/CHANGELOG.md | 2 +
.../v2/identity/GitHubActionsCredential.java | 65 ++++++++++------
.../identity/GitHubActionsCredentialTest.java | 48 +++++++-----
sdk/identity/azure-identity/CHANGELOG.md | 1 +
.../azure-identity/TROUBLESHOOTING.md | 4 +-
.../identity/GitHubActionsCredential.java | 62 ++++++++++-----
.../identity/GitHubActionsCredentialTest.java | 77 ++++++++++++++-----
7 files changed, 173 insertions(+), 86 deletions(-)
diff --git a/sdk/identity-v2/azure-identity/CHANGELOG.md b/sdk/identity-v2/azure-identity/CHANGELOG.md
index ddba9fe06e1c9..bbe477e7cb111 100644
--- a/sdk/identity-v2/azure-identity/CHANGELOG.md
+++ b/sdk/identity-v2/azure-identity/CHANGELOG.md
@@ -17,6 +17,8 @@
### Other Changes
+- Aligned `GitHubActionsCredential` OIDC response error messages with Azure Identity for JavaScript.
+
#### Dependency Updates
- Upgraded `msal4j` from `1.23.1` to `1.26.0`.
diff --git a/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredential.java b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredential.java
index ce710562f8c9c..ac12ab1d18b5b 100644
--- a/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredential.java
+++ b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredential.java
@@ -53,8 +53,7 @@ public class GitHubActionsCredential implements TokenCredential {
.setHeaders(new HttpHeaders().set(HttpHeaderName.AUTHORIZATION, "Bearer " + requestToken));
try (Response response = pipeline.send(request)) {
if (response.getStatusCode() != 200) {
- throw authenticationError(
- "GitHub OIDC request returned status code " + response.getStatusCode() + ".");
+ throw authenticationError("OIDC request returned status code " + response.getStatusCode() + ".");
}
return readAssertion(response);
}
@@ -88,34 +87,50 @@ public AccessToken getToken(TokenRequestContext request) {
private static String readAssertion(Response response) {
BinaryData body = response.getValue();
- if (body == null) {
- throw authenticationError("GitHub OIDC response must contain a nonempty string 'value'.");
+ String text = body == null ? null : body.toString();
+ if (CoreUtils.isNullOrEmpty(text)) {
+ throw authenticationError("Received null token from OIDC request.");
}
- try (JsonReader reader = JsonReader.fromString(body.toString())) {
- String assertion = reader.readObject(objectReader -> {
- String value = null;
- while (objectReader.nextToken() != JsonToken.END_OBJECT) {
- String fieldName = objectReader.getFieldName();
- objectReader.nextToken();
- if ("value".equals(fieldName)) {
- if (objectReader.currentToken() != JsonToken.STRING) {
- throw authenticationError("GitHub OIDC response must contain a string 'value'.");
+ try (JsonReader reader = JsonReader.fromString(text)) {
+ JsonToken token = reader.nextToken();
+ if (token == JsonToken.END_DOCUMENT) {
+ throw authenticationError("Failed to parse OIDC response.");
+ }
+ String assertion = null;
+ if (token == JsonToken.START_OBJECT) {
+ assertion = reader.readObject(objectReader -> {
+ String value = null;
+ while (objectReader.nextToken() != JsonToken.END_OBJECT) {
+ String fieldName = objectReader.getFieldName();
+ objectReader.nextToken();
+ if ("value".equals(fieldName)) {
+ if (objectReader.currentToken() == JsonToken.STRING) {
+ value = objectReader.getString();
+ } else {
+ value = null;
+ objectReader.skipChildren();
+ }
+ } else {
+ objectReader.skipChildren();
}
- value = objectReader.getString();
- } else {
- objectReader.skipChildren();
}
- }
- return value;
- });
- if (CoreUtils.isNullOrEmpty(assertion) || reader.nextToken() != JsonToken.END_DOCUMENT) {
- throw authenticationError("GitHub OIDC response must contain a nonempty string 'value'.");
+ return value;
+ });
+ } else {
+ reader.skipChildren();
+ }
+ if (reader.nextToken() != JsonToken.END_DOCUMENT) {
+ throw authenticationError("Failed to parse OIDC response.");
+ }
+ if (CoreUtils.isNullOrEmpty(assertion)) {
+ throw authenticationError("\"value\" field not detected in the response.");
}
return assertion;
} catch (IOException | IllegalStateException e) {
+ String message = "GitHubActionsCredential: Authentication Failed. Failed to parse OIDC response.";
throw LOGGER.throwableAtError()
- .log("GitHubActionsCredential authentication failed. Invalid GitHub OIDC response.", sanitizedCause(e),
- CredentialAuthenticationException::new);
+ .log(message, sanitizedCause(e),
+ (ignored, cause) -> new CredentialAuthenticationException(message, cause));
}
}
@@ -133,7 +148,7 @@ static RuntimeException sanitizedCause(Exception exception) {
private static CredentialAuthenticationException authenticationError(String message) {
throw LOGGER.throwableAtError()
.addKeyValue("reason", message)
- .log("GitHubActionsCredential authentication failed.",
- prefix -> new CredentialAuthenticationException(prefix + " " + message));
+ .log("GitHubActionsCredential: Authentication Failed.", ignored -> new CredentialAuthenticationException(
+ "GitHubActionsCredential: Authentication Failed. " + message));
}
}
diff --git a/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialTest.java b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialTest.java
index dd11442a77eb7..e8b87e43edbed 100644
--- a/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialTest.java
+++ b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialTest.java
@@ -17,6 +17,7 @@
import io.clientcore.core.utils.configuration.ConfigurationSource;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.UnsupportedEncodingException;
@@ -90,7 +91,9 @@ void rejectsHttpFailuresWithoutDisclosingResponse(int status) {
http.oidcBody = "{\"value\":\"response-secret-sentinel\"}";
CredentialAuthenticationException error = assertThrows(CredentialAuthenticationException.class,
() -> credentialBuilder(http).build().getToken(new TokenRequestContext().addScopes(SCOPE)));
- assertTrue(error.getMessage().contains(Integer.toString(status)));
+ assertEquals(
+ "GitHubActionsCredential: Authentication Failed. OIDC request returned status code " + status + ".",
+ error.getMessage());
assertFalse(error.getMessage().contains("response-secret-sentinel"));
assertNull(error.getCause());
assertEquals(0, http.tokenForms.size());
@@ -98,27 +101,33 @@ void rejectsHttpFailuresWithoutDisclosingResponse(int status) {
}
@ParameterizedTest
- @ValueSource(
- strings = {
- "",
- "null",
- "[]",
- "{}",
- "{\"value\":null}",
- "{\"value\":42}",
- "{\"value\":true}",
- "{\"value\":{}}",
- "{\"value\":[]}",
- "{\"value\":\"\"}",
- "response-secret-sentinel",
- "{\"value\":\"response-secret-sentinel\"",
- "{\"value\":\"response-secret-sentinel\"} trailing" })
- void rejectsInvalidResponsesWithoutDisclosingAssertions(String body) {
+ @CsvSource(
+ delimiter = '|',
+ value = {
+ "|Received null token from OIDC request.",
+ "''|Received null token from OIDC request.",
+ "' '|Failed to parse OIDC response.",
+ "null|\"value\" field not detected in the response.",
+ "[]|\"value\" field not detected in the response.",
+ "true|\"value\" field not detected in the response.",
+ "42|\"value\" field not detected in the response.",
+ "{}|\"value\" field not detected in the response.",
+ "{\"value\":null}|\"value\" field not detected in the response.",
+ "{\"value\":42}|\"value\" field not detected in the response.",
+ "{\"value\":true}|\"value\" field not detected in the response.",
+ "{\"value\":{}}|\"value\" field not detected in the response.",
+ "{\"value\":[]}|\"value\" field not detected in the response.",
+ "{\"value\":\"\"}|\"value\" field not detected in the response.",
+ "response-secret-sentinel|Failed to parse OIDC response.",
+ "{\"value\":\"response-secret-sentinel\"|Failed to parse OIDC response.",
+ "{\"value\":\"response-secret-sentinel\"} {}|Failed to parse OIDC response.",
+ "{\"value\":\"response-secret-sentinel\"} trailing|Failed to parse OIDC response." })
+ void rejectsInvalidResponsesWithoutDisclosingAssertions(String body, String reason) {
FakeHttpClient http = new FakeHttpClient();
http.oidcBody = body;
CredentialAuthenticationException error = assertThrows(CredentialAuthenticationException.class,
() -> credentialBuilder(http).build().getToken(new TokenRequestContext().addScopes(SCOPE)));
- assertFalse(error.getMessage().contains("response-secret-sentinel"));
+ assertEquals("GitHubActionsCredential: Authentication Failed. " + reason, error.getMessage());
StringWriter diagnostics = new StringWriter();
error.printStackTrace(new PrintWriter(diagnostics));
assertFalse(diagnostics.toString().contains("response-secret-sentinel"));
@@ -244,7 +253,8 @@ public Response send(HttpRequest request) {
assertEquals("Bearer runner-token-sentinel",
request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION));
AtomicBoolean closed = new AtomicBoolean();
- return new Response(request, oidcStatus, jsonHeaders(), BinaryData.fromString(oidcBody)) {
+ return new Response(request, oidcStatus, jsonHeaders(),
+ oidcBody == null ? null : BinaryData.fromString(oidcBody)) {
@Override
public void close() {
if (closed.compareAndSet(false, true)) {
diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md
index 1723ceae1e02d..737bf8c57a188 100644
--- a/sdk/identity/azure-identity/CHANGELOG.md
+++ b/sdk/identity/azure-identity/CHANGELOG.md
@@ -20,6 +20,7 @@
### Other Changes
+- Aligned `GitHubActionsCredential` OIDC response error messages with Azure Identity for JavaScript.
- Improved `AzureDeveloperCliCredential` error handling to extract meaningful messages from `azd auth token` JSON output, providing cleaner error messages to users.
#### Dependency Updates
diff --git a/sdk/identity/azure-identity/TROUBLESHOOTING.md b/sdk/identity/azure-identity/TROUBLESHOOTING.md
index d64f399a7310a..2b167058449ac 100644
--- a/sdk/identity/azure-identity/TROUBLESHOOTING.md
+++ b/sdk/identity/azure-identity/TROUBLESHOOTING.md
@@ -327,7 +327,9 @@ constructing an unconfigured credential does not defer failure to a manually com
| Invalid runner request URL | The configured URL is not an absolute HTTPS URL, or contains user information or a fragment. | Use the URL supplied by the GitHub Actions runner. |
| Unsupported authority host | There is no supported audience mapping for the authority. | Use one of the [documented cloud authorities](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity/README.md#authenticate-github-actions-workflows). Custom audiences and authorities are not supported. |
| GitHub OIDC HTTP 401/403 | GitHub rejected the runner request. | Check the job's OIDC permissions and ensure the request variables belong to the current workflow step. |
-| Invalid GitHub assertion response | The response is not HTTP 200 with a nonempty string `value`. | Check connectivity and any proxy affecting the GitHub OIDC endpoint. Do not log the response body; it can contain an assertion. |
+| `Received null token from OIDC request.` | The GitHub OIDC response body is missing or empty. | Check connectivity and any proxy affecting the GitHub OIDC endpoint. |
+| `"value" field not detected in the response.` | The JSON response does not contain a nonempty string `value`. | Check that the request reaches the GitHub OIDC endpoint. Do not log the response body; it can contain an assertion. |
+| `Failed to parse OIDC response.` | The response contains malformed JSON or trailing content. | Check connectivity and any proxy affecting the GitHub OIDC endpoint. Do not log the response body. |
| Entra reports no matching federated identity record | The presented issuer, subject, or audience does not match the app's federation configuration. | Match the actual claims for the repository/ref, including immutable subject IDs when applicable, and the audience derived from the authority host. |
See [GitHub's Azure OIDC setup guide](https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-azure)
diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java
index 2d603ec48b35f..1d351f4475bff 100644
--- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java
+++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java
@@ -12,6 +12,7 @@
import com.azure.core.http.HttpMethod;
import com.azure.core.http.HttpRequest;
import com.azure.core.http.HttpResponse;
+import com.azure.core.util.BinaryData;
import com.azure.core.util.Context;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.logging.ClientLogger;
@@ -65,8 +66,8 @@ public class GitHubActionsCredential implements TokenCredential {
.setHeader(HttpHeaderName.AUTHORIZATION, "Bearer " + requestToken);
try (HttpResponse response = pipeline.sendSync(request, Context.NONE)) {
if (response.getStatusCode() != 200) {
- throw authenticationError(
- "GitHub OIDC request returned status code " + response.getStatusCode() + ".", response);
+ throw authenticationError("OIDC request returned status code " + response.getStatusCode() + ".",
+ response);
}
return readAssertion(response);
}
@@ -132,30 +133,49 @@ public AccessToken getTokenSync(TokenRequestContext request) {
}
private static String readAssertion(HttpResponse response) {
- try (JsonReader reader = JsonProviders.createReader(response.getBodyAsBinaryData().toString())) {
- String assertion = reader.readObject(objectReader -> {
- String value = null;
- while (objectReader.nextToken() != JsonToken.END_OBJECT) {
- String fieldName = objectReader.getFieldName();
- objectReader.nextToken();
- if ("value".equals(fieldName)) {
- if (objectReader.currentToken() != JsonToken.STRING) {
- throw authenticationError("GitHub OIDC response must contain a string 'value'.", response);
+ BinaryData body = response.getBodyAsBinaryData();
+ String text = body == null ? null : body.toString();
+ if (CoreUtils.isNullOrEmpty(text)) {
+ throw authenticationError("Received null token from OIDC request.", response);
+ }
+ try (JsonReader reader = JsonProviders.createReader(text)) {
+ JsonToken token = reader.nextToken();
+ if (token == JsonToken.END_DOCUMENT) {
+ throw authenticationError("Failed to parse OIDC response.", response);
+ }
+ String assertion = null;
+ if (token == JsonToken.START_OBJECT) {
+ assertion = reader.readObject(objectReader -> {
+ String value = null;
+ while (objectReader.nextToken() != JsonToken.END_OBJECT) {
+ String fieldName = objectReader.getFieldName();
+ objectReader.nextToken();
+ if ("value".equals(fieldName)) {
+ if (objectReader.currentToken() == JsonToken.STRING) {
+ value = objectReader.getString();
+ } else {
+ value = null;
+ objectReader.skipChildren();
+ }
+ } else {
+ objectReader.skipChildren();
}
- value = objectReader.getString();
- } else {
- objectReader.skipChildren();
}
- }
- return value;
- });
- if (CoreUtils.isNullOrEmpty(assertion) || reader.nextToken() != JsonToken.END_DOCUMENT) {
- throw authenticationError("GitHub OIDC response must contain a nonempty string 'value'.", response);
+ return value;
+ });
+ } else {
+ reader.skipChildren();
+ }
+ if (reader.nextToken() != JsonToken.END_DOCUMENT) {
+ throw authenticationError("Failed to parse OIDC response.", response);
+ }
+ if (CoreUtils.isNullOrEmpty(assertion)) {
+ throw authenticationError("\"value\" field not detected in the response.", response);
}
return assertion;
} catch (IOException | IllegalStateException e) {
throw LOGGER.logExceptionAsError(new ClientAuthenticationException(
- "GitHubActionsCredential authentication failed. Invalid GitHub OIDC response.", response,
+ "GitHubActionsCredential: Authentication Failed. Failed to parse OIDC response.", response,
sanitizedCause(e)));
}
}
@@ -173,6 +193,6 @@ static RuntimeException sanitizedCause(Exception exception) {
private static RuntimeException authenticationError(String message, HttpResponse response) {
return LOGGER.logExceptionAsError(
- new ClientAuthenticationException("GitHubActionsCredential authentication failed. " + message, response));
+ new ClientAuthenticationException("GitHubActionsCredential: Authentication Failed. " + message, response));
}
}
diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java
index a80988c0cfd3e..4ee8981724aa7 100644
--- a/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java
+++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java
@@ -21,6 +21,7 @@
import com.azure.identity.util.TestUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
@@ -102,7 +103,9 @@ void rejectsHttpFailuresWithoutDisclosingResponse(int status) {
http.oidcBody = "{\"value\":\"response-secret-sentinel\"}";
ClientAuthenticationException error = assertThrows(ClientAuthenticationException.class,
() -> credentialBuilder(http).build().getTokenSync(new TokenRequestContext().addScopes(SCOPE)));
- assertTrue(error.getMessage().contains(Integer.toString(status)));
+ assertEquals(
+ "GitHubActionsCredential: Authentication Failed. OIDC request returned status code " + status + ".",
+ error.getMessage());
assertFalse(error.getMessage().contains("response-secret-sentinel"));
assertNull(error.getCause());
assertEquals(0, http.tokenForms.size());
@@ -110,27 +113,33 @@ void rejectsHttpFailuresWithoutDisclosingResponse(int status) {
}
@ParameterizedTest
- @ValueSource(
- strings = {
- "",
- "null",
- "[]",
- "{}",
- "{\"value\":null}",
- "{\"value\":42}",
- "{\"value\":true}",
- "{\"value\":{}}",
- "{\"value\":[]}",
- "{\"value\":\"\"}",
- "response-secret-sentinel",
- "{\"value\":\"response-secret-sentinel\"",
- "{\"value\":\"response-secret-sentinel\"} trailing" })
- void rejectsInvalidResponsesWithoutDisclosingAssertions(String body) {
+ @CsvSource(
+ delimiter = '|',
+ value = {
+ "|Received null token from OIDC request.",
+ "''|Received null token from OIDC request.",
+ "' '|Failed to parse OIDC response.",
+ "null|\"value\" field not detected in the response.",
+ "[]|\"value\" field not detected in the response.",
+ "true|\"value\" field not detected in the response.",
+ "42|\"value\" field not detected in the response.",
+ "{}|\"value\" field not detected in the response.",
+ "{\"value\":null}|\"value\" field not detected in the response.",
+ "{\"value\":42}|\"value\" field not detected in the response.",
+ "{\"value\":true}|\"value\" field not detected in the response.",
+ "{\"value\":{}}|\"value\" field not detected in the response.",
+ "{\"value\":[]}|\"value\" field not detected in the response.",
+ "{\"value\":\"\"}|\"value\" field not detected in the response.",
+ "response-secret-sentinel|Failed to parse OIDC response.",
+ "{\"value\":\"response-secret-sentinel\"|Failed to parse OIDC response.",
+ "{\"value\":\"response-secret-sentinel\"} {}|Failed to parse OIDC response.",
+ "{\"value\":\"response-secret-sentinel\"} trailing|Failed to parse OIDC response." })
+ void rejectsInvalidResponsesWithoutDisclosingAssertions(String body, String reason) {
FakeHttpClient http = new FakeHttpClient();
http.oidcBody = body;
ClientAuthenticationException error = assertThrows(ClientAuthenticationException.class,
() -> credentialBuilder(http).build().getTokenSync(new TokenRequestContext().addScopes(SCOPE)));
- assertFalse(error.getMessage().contains("response-secret-sentinel"));
+ assertEquals("GitHubActionsCredential: Authentication Failed. " + reason, error.getMessage());
StringWriter diagnostics = new StringWriter();
error.printStackTrace(new PrintWriter(diagnostics));
assertFalse(diagnostics.toString().contains("response-secret-sentinel"));
@@ -143,9 +152,37 @@ void asyncHttpFailureRetainsAuthenticationException() {
FakeHttpClient http = new FakeHttpClient();
http.oidcStatus = 401;
StepVerifier.create(credentialBuilder(http).build().getToken(new TokenRequestContext().addScopes(SCOPE)))
- .expectError(ClientAuthenticationException.class)
+ .expectErrorSatisfies(error -> {
+ assertTrue(error instanceof ClientAuthenticationException);
+ assertEquals("GitHubActionsCredential: Authentication Failed. OIDC request returned status code 401.",
+ error.getMessage());
+ })
+ .verify(TIMEOUT);
+ assertEquals(0, http.tokenForms.size());
+ }
+
+ @ParameterizedTest
+ @CsvSource(
+ delimiter = '|',
+ value = {
+ "|Received null token from OIDC request.",
+ "''|Received null token from OIDC request.",
+ "null|\"value\" field not detected in the response.",
+ "response-secret-sentinel|Failed to parse OIDC response." })
+ void asyncInvalidResponseRetainsAuthenticationException(String body, String reason) {
+ FakeHttpClient http = new FakeHttpClient();
+ http.oidcBody = body;
+ StepVerifier.create(credentialBuilder(http).build().getToken(new TokenRequestContext().addScopes(SCOPE)))
+ .expectErrorSatisfies(error -> {
+ assertTrue(error instanceof ClientAuthenticationException);
+ assertEquals("GitHubActionsCredential: Authentication Failed. " + reason, error.getMessage());
+ StringWriter diagnostics = new StringWriter();
+ error.printStackTrace(new PrintWriter(diagnostics));
+ assertFalse(diagnostics.toString().contains("response-secret-sentinel"));
+ })
.verify(TIMEOUT);
assertEquals(0, http.tokenForms.size());
+ assertEquals(http.oidcRequests.get(), http.closedResponses.get());
}
@ParameterizedTest
@@ -341,7 +378,7 @@ public HttpResponse sendSync(HttpRequest request, Context context) {
request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION));
AtomicBoolean closed = new AtomicBoolean();
return new MockHttpResponse(request, oidcStatus, jsonHeaders(),
- oidcBody.getBytes(StandardCharsets.UTF_8)) {
+ oidcBody == null ? null : oidcBody.getBytes(StandardCharsets.UTF_8)) {
@Override
public void close() {
if (closed.compareAndSet(false, true)) {
From 00d231af231df51202b6107ce4835568ad9de73b Mon Sep 17 00:00:00 2001
From: Victor Colin Amador
Date: Mon, 2 Nov 2026 15:12:50 -0800
Subject: [PATCH 09/11] Use the default authority for GitHub Actions live tests
---
.github/workflows/identity-github-actions-credential.yml | 1 -
1 file changed, 1 deletion(-)
diff --git a/.github/workflows/identity-github-actions-credential.yml b/.github/workflows/identity-github-actions-credential.yml
index 5abd28abcf5d8..a92490f5eedde 100644
--- a/.github/workflows/identity-github-actions-credential.yml
+++ b/.github/workflows/identity-github-actions-credential.yml
@@ -28,7 +28,6 @@ jobs:
env:
AZURE_TENANT_ID: ${{ vars.AZURE_IDENTITY_GITHUB_ACTIONS_TENANT_ID }}
AZURE_CLIENT_ID: ${{ vars.AZURE_IDENTITY_GITHUB_ACTIONS_CLIENT_ID }}
- AZURE_AUTHORITY_HOST: https://login.microsoftonline.com/
AZURE_TEST_MODE: LIVE
RUN_GITHUB_ACTIONS_CREDENTIAL_LIVE_TESTS: 'true'
SDK_COORDINATES: ${{ matrix.package }}
From 61b37e9e5c6a5b259ba6812f0b2f8dd242cf3399 Mon Sep 17 00:00:00 2001
From: Victor Colin Amador
Date: Tue, 3 Nov 2026 18:40:18 -0800
Subject: [PATCH 10/11] Removed unnecessary changelog entries
---
sdk/identity-v2/azure-identity/CHANGELOG.md | 2 --
sdk/identity/azure-identity/CHANGELOG.md | 1 -
2 files changed, 3 deletions(-)
diff --git a/sdk/identity-v2/azure-identity/CHANGELOG.md b/sdk/identity-v2/azure-identity/CHANGELOG.md
index bbe477e7cb111..ddba9fe06e1c9 100644
--- a/sdk/identity-v2/azure-identity/CHANGELOG.md
+++ b/sdk/identity-v2/azure-identity/CHANGELOG.md
@@ -17,8 +17,6 @@
### Other Changes
-- Aligned `GitHubActionsCredential` OIDC response error messages with Azure Identity for JavaScript.
-
#### Dependency Updates
- Upgraded `msal4j` from `1.23.1` to `1.26.0`.
diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md
index 737bf8c57a188..1723ceae1e02d 100644
--- a/sdk/identity/azure-identity/CHANGELOG.md
+++ b/sdk/identity/azure-identity/CHANGELOG.md
@@ -20,7 +20,6 @@
### Other Changes
-- Aligned `GitHubActionsCredential` OIDC response error messages with Azure Identity for JavaScript.
- Improved `AzureDeveloperCliCredential` error handling to extract meaningful messages from `azd auth token` JSON output, providing cleaner error messages to users.
#### Dependency Updates
From 394223ee31cf23b13c18d920f684684061c5cdcf Mon Sep 17 00:00:00 2001
From: Victor Colin Amador
Date: Wed, 4 Nov 2026 16:22:23 -0800
Subject: [PATCH 11/11] Updated CHANGELOGs
---
sdk/identity-v2/azure-identity/CHANGELOG.md | 9 ---------
sdk/identity/azure-identity/CHANGELOG.md | 6 +++---
2 files changed, 3 insertions(+), 12 deletions(-)
diff --git a/sdk/identity-v2/azure-identity/CHANGELOG.md b/sdk/identity-v2/azure-identity/CHANGELOG.md
index ddba9fe06e1c9..9c6737b549aae 100644
--- a/sdk/identity-v2/azure-identity/CHANGELOG.md
+++ b/sdk/identity-v2/azure-identity/CHANGELOG.md
@@ -4,19 +4,10 @@
### Features Added
-- Added `GitHubActionsCredential` and `GitHubActionsCredentialBuilder` for authentication using GitHub Actions OIDC federation.
-- Added support for user-assigned managed identities on Azure Arc in `ManagedIdentityCredential` and `DefaultAzureCredential`.
-
### Breaking Changes
### Bugs Fixed
-- Fixed client-credentials authentication to acquire a new token when handling a Continuous Access Evaluation (CAE) claims challenge.
-- Fixed `DefaultAzureCredential` failing after a credential successfully acquired a token.
-- Aligned user-assigned managed identity validation for Azure Service Fabric with `azure-identity`.
-
### Other Changes
#### Dependency Updates
-
-- Upgraded `msal4j` from `1.23.1` to `1.26.0`.
diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md
index f5ede4b7df96a..1063d2de929d1 100644
--- a/sdk/identity/azure-identity/CHANGELOG.md
+++ b/sdk/identity/azure-identity/CHANGELOG.md
@@ -4,14 +4,14 @@
### Features Added
-- Added `GitHubActionsCredential` and `GitHubActionsCredentialBuilder` for authentication using GitHub Actions OIDC federation.
+- Added `GitHubActionsCredential` and `GitHubActionsCredentialBuilder` for authentication using GitHub Actions OIDC federation. ([#50916](https://github.com/Azure/azure-sdk-for-java/pull/50916))
### Breaking Changes
### Bugs Fixed
-- Fixed an initial OIDC request failure preventing later authentication attempts with the same `AzurePipelinesCredential` or `GitHubActionsCredential` instance.
-- Fixed client-credentials authentication to acquire a new token when handling a Continuous Access Evaluation (CAE) claims challenge.
+- Fixed an initial OIDC request failure preventing later authentication attempts with the same `AzurePipelinesCredential` or `GitHubActionsCredential` instance. ([#50916](https://github.com/Azure/azure-sdk-for-java/pull/50916))
+- Fixed client-credentials authentication to acquire a new token when handling a Continuous Access Evaluation (CAE) claims challenge. ([#50916](https://github.com/Azure/azure-sdk-for-java/pull/50916))`
### Other Changes