Skip to content

[Profile] az login: Add --federated-credential-provider to refresh OIDC federated tokens automatically - #34497

Open
MaddyMicrosoft wants to merge 25 commits into
devfrom
feature/oidc-token-refresh
Open

MaddyMicrosoft wants to merge 25 commits into
devfrom
feature/oidc-token-refresh

Conversation

@MaddyMicrosoft

@MaddyMicrosoft MaddyMicrosoft commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

🤖 PR Validation — ⚠️ Review suggested

Breaking Changes Tests Suppressions
⚠️ None ️✔️ 130/130 ️✔️ None
⚠️AzureCLI-BreakingChangeTest
⚠️profile
rule cmd_name rule_message suggest_message
⚠️ 1006 - ParaAdd login cmd login added parameter federated_credential_audience
⚠️ 1006 - ParaAdd login cmd login added parameter federated_credential_provider

Related command
az login

Description
CI/CD jobs that log in with --federated-token fail with AADSTS700024 once that OIDC token expires, because Azure CLI can only reuse the one token it was given.

This PR adds --federated-credential-provider. Instead of passing a token, the user names the CI/CD provider, and Azure CLI gets a fresh OIDC token from it whenever it needs a new access token. The option name and values match azd auth login --federated-credential-provider.

New options:

Option Alias Values
--federated-credential-provider --fed-cred-provider github, azure-pipelines
--federated-credential-audience --fed-cred-audience Audience to request from GitHub. Defaults to api://AzureADTokenExchange. Needed for sovereign clouds (for example api://AzureADTokenExchangeUSGov) or custom audiences. Only supported with github.

Provider requirements:

  • github: the workflow or job needs the id-token: write permission, which makes GitHub set ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN.
  • azure-pipelines: run az in an AzureCLI@2 task, which sets AZURESUBSCRIPTION_SERVICE_CONNECTION_ID, and map SYSTEM_ACCESSTOKEN: $(System.AccessToken) into the step's env. The request URL comes from the predefined System.OidcRequestUri variable. Azure Pipelines sets the token audience itself, so --federated-credential-audience is rejected.

How it works:

  • az login saves federated_credential_provider, and the audience if given, with the service principal. No token is saved.
  • MSAL gets a client_assertion callback instead of a token string. MSAL calls it whenever it needs a new access token, and the callback gets a fresh ID token from the provider. Later az commands rebuild the callback from the saved login.
  • The provider code is in a new module, azure/cli/core/auth/federated_credential.py.

Usage checks:

  • --federated-credential-provider requires --service-principal and can't be combined with --federated-token, --password or --certificate.
  • --federated-credential-audience requires --federated-credential-provider github.

Security:

  • No shell commands or user-supplied programs are run. The earlier --federated-token-callback option was removed from this PR.
  • Azure CLI only sends HTTPS requests to the token endpoints the CI system provides in environment variables, with (10s, 30s) connect/read timeouts.
  • The token is never logged or written to disk.

--federated-token behaves exactly as before.

Testing Guide

Usage errors (no CI environment needed):

az login --service-principal -u APP_ID --tenant TENANT_ID --federated-credential-provider azure-pipelines --federated-credential-audience api://custom
# ERROR: usage error: '--federated-credential-audience' requires '--federated-credential-provider github'. Azure Pipelines sets the token audience itself.

az login --service-principal -u APP_ID --tenant TENANT_ID --federated-credential-provider github
# Outside GitHub Actions:
# ERROR: '--federated-credential-provider github' requires environment variable(s): ACTIONS_ID_TOKEN_REQUEST_URL, ACTIONS_ID_TOKEN_REQUEST_TOKEN. Grant the workflow or job the 'id-token: write' permission.

GitHub Actions:

permissions:
  id-token: write
steps:
  - run: |
      az login --service-principal -u "$CLIENT_ID" --tenant "$TENANT_ID" --federated-credential-provider github
      sleep 720  # longer than the OIDC token lifetime
      az account get-access-token --resource https://storage.azure.com  # succeeds; previously AADSTS700024

Azure Pipelines:

- task: AzureCLI@2
  inputs:
    azureSubscription: my-service-connection
    scriptType: bash
    scriptLocation: inlineScript
    inlineScript: |
      az login --service-principal -u "$AZURESUBSCRIPTION_CLIENT_ID" --tenant "$AZURESUBSCRIPTION_TENANT_ID" --federated-credential-provider azure-pipelines
      ./long-running-deploy.sh
  env:
    SYSTEM_ACCESSTOKEN: $(System.AccessToken)

Validation:

  • Unit tests for the provider token requests, the saved login and the argument checks
  • GitHub Actions end to end on an earlier revision of this PR (option then called --federated-identity): a token refresh 12 minutes after login, and a ~54-minute run getting tokens for several resources
  • GitHub Actions end to end with --federated-credential-provider github
  • Azure Pipelines end to end with --federated-credential-provider azure-pipelines

History Notes

[Profile] az login: Add --federated-credential-provider to automatically refresh OIDC federated tokens in GitHub Actions and Azure Pipelines


This checklist is used to make sure that common guidelines for a pull request are followed.

MaddyMicrosoft and others added 15 commits October 9, 2026 01:56
… federated tokens

Static `--federated-token` values expire in ~10 minutes and cannot be refreshed,
so long-running CI/CD tasks fail with `AADSTS700024: Client assertion is not
within its valid time range`.

This registers a callable client_assertion with MSAL (the documented, recommended
interface) so an expired OIDC ID token is transparently re-fetched on every token
acquisition, including in later `az` processes. Wiring:

- New `FEDERATED_IDENTITY` sentinel persisted as the SP entry's client_assertion.
- `ServicePrincipalAuth.get_msal_client_credential()` resolves that sentinel to a
  provider dispatcher, `get_federated_id_token()`, instead of a static string.
- Dispatcher implements GitHub Actions; other environments raise a clear error
  pointing at `--federated-token`. Azure DevOps is a planned follow-up (#28708).
- New `az login --federated-identity` flag, mutually exclusive with
  `--federated-token` and only valid with `--service-principal`.

Adds unit tests covering the sentinel-to-callable resolution, the GitHub fetch
(success and HTTP error), and the unsupported/no-provider branches.

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…token refresh

Extends `--federated-identity` (GitHub Actions only) to also refresh OIDC federated
tokens on Azure DevOps Pipelines, so long-running pipeline tasks no longer fail with
`AADSTS700024`.

The provider dispatcher now detects Azure DevOps and POSTs to the pipeline oidctoken
API, following the documented Azure DevOps / azure-identity `AzurePipelinesCredential`
contract. Because the refresh runs in a later `az` process, the three required inputs
are read from the environment:

- request URL:  ARM_OIDC_REQUEST_URL, else SYSTEM_OIDCREQUESTURI
- access token: ARM_OIDC_REQUEST_TOKEN, else SYSTEM_ACCESSTOKEN (System.AccessToken)
- service conn: ARM_OIDC_AZURE_SERVICE_CONNECTION_ID

Missing variables produce a clear, actionable error. Adds unit tests for the Azure
DevOps success path, missing-environment handling, and updates the help text.

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…oken refresh

Adds a provider-agnostic escape hatch alongside the built-in `--federated-identity`
providers. `--federated-token-callback <command>` takes any command that prints a
fresh OIDC token to stdout; Azure CLI wraps it as the MSAL client_assertion callable
and re-runs it on demand, so token refresh works with any CI/CD system (not just the
built-in GitHub Actions / Azure DevOps providers) without platform-specific logic in
the CLI.

- The command is persisted (client_assertion_callback) so later `az` processes rebuild
  the callable and refresh independently.
- Mutually exclusive with --federated-token and --federated-identity; service principal
  only. Clear errors on non-zero exit or empty output. The token value is never logged.

The three flags now cover the full spectrum: static token (--federated-token),
built-in providers (--federated-identity), and universal callback
(--federated-token-callback).

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Harden --federated-token-callback: parse the command into an argv list and run it
  without a shell (shell=False), so a tampered token cache cannot become arbitrary
  code execution. Users needing pipes/redirection use a script or wrap in bash -c.
- Reject combining --federated-token/--federated-identity/--federated-token-callback
  with --password or --certificate (previously the secret silently won and refresh
  was silently disabled).
- Fix the GitHub OIDC request URL to append the audience with the correct separator
  when the URL has no existing query string.
- Correct the misleading --service-principal usage error to list all credential modes.
- Align --federated-identity help text with the actual mutual-exclusion validation.
- Add tests for the no-shell argv behavior and the query-less GitHub URL case.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…on-length linter

The --federated-token-callback option (26 chars) exceeds azure-cli's 22-char
option-length threshold, so add the shorter --federated-token-cmd alias.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Per MSAL guidance, the client_assertion callback must be thread-safe because
concurrent token requests may invoke it simultaneously. Serialize the provider
dispatcher (get_federated_id_token) and the command-based callback with locks so
overlapping refreshes cannot race (duplicate HTTP fetch / subprocess run). Adds a
concurrency test asserting the callback never executes overlapping invocations.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Code-review follow-ups on the OIDC token-refresh feature:

- Add an explicit connect/read timeout to the GitHub Actions and Azure DevOps OIDC
  token requests via a shared _oidc_http_request helper. Without it, a stalled
  connection would hang token acquisition (and, for --federated-identity, every
  concurrent refresh thread holding the lock) indefinitely on a long-running CI job.
  Timeout and connection failures now raise a clear CLIError.
- Parse the --federated-token-callback command with POSIX rules on every platform.
  The previous posix=False path on Windows left literal quote characters in argv, so a
  quoted argument containing spaces (e.g. an audience) reached the program corrupted.
  POSIX parsing handles quoting correctly and consistently; the Windows backslash
  caveat is documented in the help text and docstring.

Adds tests for the request timeout path and quoted-argument parsing.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
… federated tokens

Static `--federated-token` values expire in ~10 minutes and cannot be refreshed,
so long-running CI/CD tasks fail with `AADSTS700024: Client assertion is not
within its valid time range`.

This registers a callable client_assertion with MSAL (the documented, recommended
interface) so an expired OIDC ID token is transparently re-fetched on every token
acquisition, including in later `az` processes. Wiring:

- New `FEDERATED_IDENTITY` sentinel persisted as the SP entry's client_assertion.
- `ServicePrincipalAuth.get_msal_client_credential()` resolves that sentinel to a
  provider dispatcher, `get_federated_id_token()`, instead of a static string.
- Dispatcher implements GitHub Actions; other environments raise a clear error
  pointing at `--federated-token`. Azure DevOps is a planned follow-up (#28708).
- New `az login --federated-identity` flag, mutually exclusive with
  `--federated-token` and only valid with `--service-principal`.

Adds unit tests covering the sentinel-to-callable resolution, the GitHub fetch
(success and HTTP error), and the unsupported/no-provider branches.

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…token refresh

Extends `--federated-identity` (GitHub Actions only) to also refresh OIDC federated
tokens on Azure DevOps Pipelines, so long-running pipeline tasks no longer fail with
`AADSTS700024`.

The provider dispatcher now detects Azure DevOps and POSTs to the pipeline oidctoken
API, following the documented Azure DevOps / azure-identity `AzurePipelinesCredential`
contract. Because the refresh runs in a later `az` process, the three required inputs
are read from the environment:

- request URL:  ARM_OIDC_REQUEST_URL, else SYSTEM_OIDCREQUESTURI
- access token: ARM_OIDC_REQUEST_TOKEN, else SYSTEM_ACCESSTOKEN (System.AccessToken)
- service conn: ARM_OIDC_AZURE_SERVICE_CONNECTION_ID

Missing variables produce a clear, actionable error. Adds unit tests for the Azure
DevOps success path, missing-environment handling, and updates the help text.

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…oken refresh

Adds a provider-agnostic escape hatch alongside the built-in `--federated-identity`
providers. `--federated-token-callback <command>` takes any command that prints a
fresh OIDC token to stdout; Azure CLI wraps it as the MSAL client_assertion callable
and re-runs it on demand, so token refresh works with any CI/CD system (not just the
built-in GitHub Actions / Azure DevOps providers) without platform-specific logic in
the CLI.

- The command is persisted (client_assertion_callback) so later `az` processes rebuild
  the callable and refresh independently.
- Mutually exclusive with --federated-token and --federated-identity; service principal
  only. Clear errors on non-zero exit or empty output. The token value is never logged.

The three flags now cover the full spectrum: static token (--federated-token),
built-in providers (--federated-identity), and universal callback
(--federated-token-callback).

Partially addresses #28708

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Harden --federated-token-callback: parse the command into an argv list and run it
  without a shell (shell=False), so a tampered token cache cannot become arbitrary
  code execution. Users needing pipes/redirection use a script or wrap in bash -c.
- Reject combining --federated-token/--federated-identity/--federated-token-callback
  with --password or --certificate (previously the secret silently won and refresh
  was silently disabled).
- Fix the GitHub OIDC request URL to append the audience with the correct separator
  when the URL has no existing query string.
- Correct the misleading --service-principal usage error to list all credential modes.
- Align --federated-identity help text with the actual mutual-exclusion validation.
- Add tests for the no-shell argv behavior and the query-less GitHub URL case.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…on-length linter

The --federated-token-callback option (26 chars) exceeds azure-cli's 22-char
option-length threshold, so add the shorter --federated-token-cmd alias.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Per MSAL guidance, the client_assertion callback must be thread-safe because
concurrent token requests may invoke it simultaneously. Serialize the provider
dispatcher (get_federated_id_token) and the command-based callback with locks so
overlapping refreshes cannot race (duplicate HTTP fetch / subprocess run). Adds a
concurrency test asserting the callback never executes overlapping invocations.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Code-review follow-ups on the OIDC token-refresh feature:

- Add an explicit connect/read timeout to the GitHub Actions and Azure DevOps OIDC
  token requests via a shared _oidc_http_request helper. Without it, a stalled
  connection would hang token acquisition (and, for --federated-identity, every
  concurrent refresh thread holding the lock) indefinitely on a long-running CI job.
  Timeout and connection failures now raise a clear CLIError.
- Parse the --federated-token-callback command with POSIX rules on every platform.
  The previous posix=False path on Windows left literal quote characters in argv, so a
  quoted argument containing spaces (e.g. an audience) reached the program corrupted.
  POSIX parsing handles quoting correctly and consistently; the Windows backslash
  caveat is documented in the help text and docstring.

Adds tests for the request timeout path and quoted-argument parsing.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved callback execution flaws can enable Windows executable hijacking and expose credentials through error reporting.

4 open issues
What changed in this PR

This PR extends Azure CLI service-principal login to refresh OIDC federated assertions on demand, helping long-running CI/CD jobs continue after the initial assertion expires.

Changes:

  • Adds provider-based refresh for GitHub Actions and Azure DevOps, plus a user-supplied token command.
  • Adds credential validation, persisted refresh configuration, HTTP timeouts, and serialized callback execution.
  • Adds unit tests for provider retrieval, callback execution, and selected failure paths.
File Description
src/​azure-cli/​azure/​cli/​command_modules/​profile/​custom.py Validates refresh options and forwards credentials to authentication.
src/​azure-cli/​azure/​cli/​command_modules/​profile/​__init__.py Registers refresh flags, callback alias, and help text.
src/​azure-cli-core/​azure/​cli/​core/​auth/​tests/​test_identity.py Tests refresh credentials, providers, and callback behavior.
src/​azure-cli-core/​azure/​cli/​core/​auth/​identity.py Persists refresh settings and implements provider and command callbacks.

Review effort: Balanced

@yonzhan

Copy link
Copy Markdown
Collaborator

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@x-engineering-agent

Copy link
Copy Markdown
Contributor

MaddyMicrosoft Could you please fix the CI failure first?

@MaddyMicrosoft MaddyMicrosoft changed the title [Profile] az login: Support automatic OIDC federated token refresh [Profile] az login: Support automatic OIDC federated token refresh Nov 25, 2026
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@isra-fel

Copy link
Copy Markdown
Member

Few things I care most:

  1. Can we use the same solution for azure powershell and azclips
  2. Can it extend to ADO pipelines
  3. Security. Is the solution prone to code injection?

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@MaddyMicrosoft

Copy link
Copy Markdown
Member Author
  1. I dont see why not, we will need to look at the code. I dont have data on ADO but GHA login PS is barely used. <100 calls a day generally vs
  2. It already works for ADO.
  3. Potentially with callback, I am going to remove it, and we can add it as an advanced feature later/ do an in-depth analysis of the risk

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Federated login and token refresh can fail because the audience is hard-coded and ARM_OIDC_REQUEST_URL values with existing query parameters are handled incorrectly.

2 open issues
4 resolved since last review

Review effort: Balanced

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@x-engineering-agent

Copy link
Copy Markdown
Contributor

@x-engineering-agent

Copy link
Copy Markdown
Contributor

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should move FID code elsewhere cause identity.py is pretty long

MaddyMicrosoft and others added 2 commits November 27, 2026 05:15
…ovider

Add azure.cli.core.auth.federated_credential with get_federated_id_token(provider, audience),
for use as MSAL's client_assertion callback so a fresh OIDC ID token is fetched whenever a new
access token is needed.

Providers:
- github: reads ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN (set only when
  the job has the 'id-token: write' permission) and requests the given audience, defaulting
  to api://AzureADTokenExchange.
- azure-pipelines: calls the oidctoken API at SYSTEM_OIDCREQUESTURI, authenticated with
  SYSTEM_ACCESSTOKEN, for the service connection in AZURESUBSCRIPTION_SERVICE_CONNECTION_ID
  (set by the AzureCLI@2 task). The API has no audience parameter, so none is sent.

Requests use (10s, 30s) connect/read timeouts and are serialized with a lock. Missing
environment variables, HTTP errors, timeouts and non-JSON responses raise a CLIError. The token
is never logged.

The provider is chosen explicitly rather than detected from the environment. az login is wired
to this module in the next commit.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…d-credential-provider`

The user now names the CI/CD provider instead of Azure CLI detecting it from the environment,
matching `azd auth login --federated-credential-provider`.

- --federated-credential-provider (--fed-cred-provider): github or azure-pipelines
- --federated-credential-audience (--fed-cred-audience): audience to request from GitHub;
  defaults to api://AzureADTokenExchange. Replaces --federated-identity-audience/--fid-audience.

Usage checks:
- --federated-credential-provider requires --service-principal and can't be combined with
  --federated-token, --password or --certificate
- --federated-credential-audience requires --federated-credential-provider github, because
  Azure Pipelines sets the token audience itself
- --federated-token with --password or --certificate is no longer rejected, as before this
  feature

The service principal entry now saves federated_credential_provider and an optional
federated_credential_audience, instead of a FEDERATED_IDENTITY marker in client_assertion.
identity.py builds the MSAL callback from these values using the federated_credential module,
and the provider detection and token-request code is removed from identity.py.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@MaddyMicrosoft MaddyMicrosoft changed the title [Profile] az login: Support automatic OIDC federated token refresh [Profile] az login: Add --federated-credential-provider to refresh OIDC federated tokens automatically Nov 27, 2026
Add a paragraph to the az login long summary explaining that --federated-credential-provider
gets a fresh OIDC token from GitHub Actions or Azure Pipelines whenever Azure CLI needs one,
so long-running jobs don't fail with AADSTS700024.

Add examples for GitHub Actions, GitHub Actions with the Azure US Government audience, and
an Azure Pipelines AzureCLI@2 task.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Both providers can send CI bearer credentials to HTTP endpoints in cleartext; HTTPS validation and disabled automatic redirects are needed to prevent credential exposure.

1 open issue
2 resolved since last review

Review effort: Balanced

Comment on lines +74 to +76
import requests
try:
response = method(url, headers=headers, timeout=_OIDC_HTTP_TIMEOUT)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants