Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions .github/workflows/identity-github-actions-credential.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
name: Identity GitHub Actions credential

on:
push:
branches:
- vcolin7-github-actions-credential
workflow_dispatch:

permissions:
contents: read

jobs:
authenticate:
name: ${{ matrix.package }}
runs-on: ubuntu-24.04
timeout-minutes: 30
permissions:
contents: read
id-token: write
strategy:
fail-fast: false
matrix:
include:
- package: com.azure:azure-identity
pom: sdk/identity/azure-identity/pom.xml
- package: com.azure.v2:azure-identity
pom: sdk/identity-v2/azure-identity/pom.xml
env:
AZURE_TENANT_ID: ${{ vars.AZURE_IDENTITY_GITHUB_ACTIONS_TENANT_ID }}
AZURE_CLIENT_ID: ${{ vars.AZURE_IDENTITY_GITHUB_ACTIONS_CLIENT_ID }}
AZURE_TEST_MODE: LIVE
RUN_GITHUB_ACTIONS_CREDENTIAL_LIVE_TESTS: 'true'
SDK_COORDINATES: ${{ matrix.package }}
SDK_POM: ${{ matrix.pom }}
steps:
- name: Check test identity configuration
shell: bash
run: |
if [[ -z "$AZURE_TENANT_ID" || -z "$AZURE_CLIENT_ID" ]]; then
echo "::error::Set AZURE_IDENTITY_GITHUB_ACTIONS_TENANT_ID and AZURE_IDENTITY_GITHUB_ACTIONS_CLIENT_ID repository variables."
exit 1
fi

- name: Checkout code
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
persist-credentials: false

- name: Set up JDK 25
uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
with:
distribution: temurin
java-version: '25'
cache: maven

- name: Build the selected SDK and its dependencies
shell: bash
run: >
mvn -B -ntp -f pom.xml -pl "$SDK_COORDINATES" -am
install -DskipTests -Djacoco.skip=true -Dgpg.skip=true

- name: Authenticate through GitHub OIDC and Microsoft Entra
shell: bash
run: >
mvn -B -ntp -f "$SDK_POM"
test -Dtest=GitHubActionsCredentialLiveTest
7 changes: 0 additions & 7 deletions sdk/identity-v2/azure-identity/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,10 @@

### Features Added

- Added support for user-assigned managed identities on Azure Arc in `ManagedIdentityCredential` and `DefaultAzureCredential`.

### Breaking Changes

### Bugs Fixed

- 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`.
64 changes: 64 additions & 0 deletions sdk/identity-v2/azure-identity/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,71 @@ To take dependency on a particular version of the library that isn't present in

## Examples

### Authenticate GitHub Actions workflows

`com.azure.v2.identity.GitHubActionsCredential` authenticates through GitHub Actions OIDC federation.
Configure an Entra application's federated identity credential to trust your GitHub workflow's issuer, subject,
and audience, following [GitHub's Azure OIDC setup guide][github_oidc].

The workflow needs `permissions: id-token: write`. Set `AZURE_TENANT_ID` and `AZURE_CLIENT_ID` in the workflow
environment. GitHub supplies `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN`; do not
configure those values as repository secrets or print them. No client secret, certificate, or `azure/login`
step is required.

```java readme-sample-v2-github-actions-credential
TokenCredential gitHubCredential = new GitHubActionsCredentialBuilder().build();
```

The builder also accepts explicit IDs, which override the environment variables:

```java readme-sample-v2-github-actions-credential-explicit
TokenCredential explicitCredential
= new GitHubActionsCredentialBuilder().tenantId("<tenant-id>").clientId("<client-id>").build();
```

The v2 credential uses `com.azure.v2.core.credentials.TokenCredential` and its synchronous `getToken` API.
It is not included in `DefaultAzureCredential`.

An explicit `authorityHost` takes precedence over `AZURE_AUTHORITY_HOST`, followed by Azure Public.
The assertion audience is derived from the effective authority; configure the same audience on 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` |

### Run the opt-in end-to-end test

The [Identity GitHub Actions credential workflow][github_oidc_workflow] builds both Identity
packages from source and requests a public-cloud ARM access token from each, without calling Azure resources or
logging token values. It runs on pushes to `vcolin7-github-actions-credential` and also supports manual dispatch.

Configure a test application's federated identity credential for your repository's actual issuer and subject
(including immutable IDs when applicable), the ref to be tested, and audience `api://AzureADTokenExchange`.
Set repository variables `AZURE_IDENTITY_GITHUB_ACTIONS_TENANT_ID` and `AZURE_IDENTITY_GITHUB_ACTIONS_CLIENT_ID`,
then push the workflow and SDK changes to `vcolin7-github-actions-credential` in your fork.
For manual runs, the workflow must first be present on the repository's default branch; you can then dispatch
it on a trusted ref. The workflow does not create cloud resources or repository settings.

The dedicated live test is skipped unless `RUN_GITHUB_ACTIONS_CREDENTIAL_LIVE_TESTS=true`, `AZURE_TEST_MODE=LIVE`,
and `GITHUB_ACTIONS=true`. The workflow supplies those settings.

## Troubleshooting

`GitHubActionsCredentialBuilder.build()` raises `CredentialUnavailableException` when required configuration is
missing, the runner request URL is invalid, or the authority has no supported audience mapping. Supply the Azure IDs
through the builder or environment and ensure the job has `permissions: id-token: write`. The runner request URL
must be an absolute HTTPS URL.

GitHub OIDC HTTP or response-parsing failures raise `CredentialAuthenticationException`. For HTTP 401/403,
check the workflow permissions and run the SDK in the step where GitHub provides its OIDC variables.
For Entra federation errors, verify that the issuer, subject, and audience match the application's federated
identity credential. Error messages do not include the assertion or raw OIDC response body.

## Next steps

Expand All @@ -47,3 +109,5 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con

<!-- LINKS -->
[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/
[github_oidc]: https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-azure
[github_oidc_workflow]: https://github.com/Azure/azure-sdk-for-java/blob/main/.github/workflows/identity-github-actions-credential.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.v2.identity;

import com.azure.v2.core.credentials.TokenCredential;
import com.azure.v2.core.credentials.TokenRequestContext;
import com.azure.v2.identity.exceptions.CredentialAuthenticationException;
import com.azure.v2.identity.implementation.models.ConfidentialClientOptions;
import io.clientcore.core.credentials.oauth.AccessToken;
import io.clientcore.core.http.models.HttpHeaderName;
import io.clientcore.core.http.models.HttpHeaders;
import io.clientcore.core.http.models.HttpMethod;
import io.clientcore.core.http.models.HttpRequest;
import io.clientcore.core.http.models.Response;
import io.clientcore.core.instrumentation.logging.ClientLogger;
import io.clientcore.core.models.CoreException;
import io.clientcore.core.models.binarydata.BinaryData;
import io.clientcore.core.serialization.json.JsonReader;
import io.clientcore.core.serialization.json.JsonToken;
import io.clientcore.core.utils.CoreUtils;

import java.io.IOException;

/**
* Authenticates an application in GitHub Actions using an OIDC federated identity credential.
*
* <p>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}.</p>
*
* <p>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}.</p>
*
* <!-- src_embed com.azure.v2.identity.credential.githubactionscredential.construct -->
* <pre>
* GitHubActionsCredential credential = new GitHubActionsCredentialBuilder&#40;&#41;.build&#40;&#41;;
* </pre>
* <!-- end com.azure.v2.identity.credential.githubactionscredential.construct -->
*
* @see GitHubActionsCredentialBuilder
*/
public class GitHubActionsCredential implements TokenCredential {
private static final ClientLogger LOGGER = new ClientLogger(GitHubActionsCredential.class);
private final ClientAssertionCredential clientAssertionCredential;

GitHubActionsCredential(String requestUrl, String requestToken, ConfidentialClientOptions options) {
options.setClientAssertionFunction(pipeline -> {
HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET)
.setUri(requestUrl)
.setHeaders(new HttpHeaders().set(HttpHeaderName.AUTHORIZATION, "Bearer " + requestToken));
try (Response<BinaryData> response = pipeline.send(request)) {
if (response.getStatusCode() != 200) {
throw authenticationError("OIDC request returned status code " + response.getStatusCode() + ".");
}
return readAssertion(response);
}
});
clientAssertionCredential = new ClientAssertionCredential(options);
}

/**
* Acquires an access token, using the token cache when possible.
*
* <p>Requests with a Continuous Access Evaluation (CAE) claims challenge acquire a new token instead of reusing a
* cached token.</p>
*
* @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.
*/
@Override
public AccessToken getToken(TokenRequestContext request) {
try {
return clientAssertionCredential.getToken(request);
} catch (CoreException e) {
// Preserve the OIDC failure category through client-assertion delegation.
Throwable cause = e.getCause();
if (cause instanceof CredentialAuthenticationException) {
throw (CredentialAuthenticationException) cause;
}
throw e;
}
}

private static String readAssertion(Response<BinaryData> response) {
Comment thread
vcolin7 marked this conversation as resolved.
Resolved
BinaryData body = response.getValue();
String text = body == null ? null : body.toString();
if (CoreUtils.isNullOrEmpty(text)) {
throw authenticationError("Received null token from OIDC request.");
}
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();
}
}
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(message, sanitizedCause(e),
(ignored, cause) -> new CredentialAuthenticationException(message, cause));
}
}

// 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 CredentialAuthenticationException authenticationError(String message) {
throw LOGGER.throwableAtError()
.addKeyValue("reason", message)
.log("GitHubActionsCredential: Authentication Failed.", ignored -> new CredentialAuthenticationException(
"GitHubActionsCredential: Authentication Failed. " + message));
}
}
Loading
Loading