Aspirerelease/17.0
Watch Aspire live streams文档试用 Aspire

Configure Entra ID client credentials

此内容尚不支持你的语言。

An app that acquires tokens for itself, or that redeems authorization codes, is a confidential client and needs a client credential. An API that only validates incoming tokens needs none. Each credential method appends an entry to the ClientCredentials array that referencing apps receive, such as AzureAd__ClientCredentials__0__SourceType. You can configure more than one credential to form a fallback chain.

Aspire doesn’t create, store, or rotate client secrets or certificates for you, except for the local developer certificate. The other methods describe a secret or certificate that already exists. Managed identity federation uses no secret or certificate. Aspire creates only the federated credential that establishes trust.

CredentialMethodRegistrationsApplies when
Local developer certificateRunWithLocalDeveloperCertificateCredentialCreatedRunning
Managed identity that Aspire trustsPublishWithFederatedManagedIdentityCredentialCreatedPublishing
Client secretWithClientSecretCreated and existingRunning and publishing
Managed identity that you configuredWithFederatedManagedIdentityCredentialCreated and existingRunning and publishing
Key Vault certificateWithCertificateFromKeyVaultCreated and existingRunning and publishing
Certificate storeWithCertificateThumbprint, WithCertificateDistinguishedNameCreated and existingRunning and publishing
Certificate file or signed assertion fileTypeScript: withCertificateFromFile, withSignedAssertionFile. C#: WithCredentialCreated and existingRunning and publishing

For registrations that Aspire creates, opt in to a short-lived local certificate instead of copying a client secret. Aspire creates the certificate, registers only its public key with Microsoft Entra ID, and passes the private key to referencing apps.

Combine the method with managed identity federation so the app has a credential both locally and when deployed. The local method does nothing when you publish.

apphost.mts
const entraWeb = await builder.addEntraIdApplication("entra-web")
.runWithLocalDeveloperCertificateCredential()
.publishWithFederatedManagedIdentityCredential();
const web = await builder.addDotnetProject("web", "../Web/Web.csproj");
await web.withReference(entraWeb);
  • The certificate is valid for 48 hours. Aspire renews it when the AppHost starts and 24 hours or less remain. There’s no background renewal, so restart long development sessions before the certificate expires.
  • Aspire stores the certificate, including its private key, at dev-certs/Entra/<resource-name>.pfx in the AppHost’s Aspire store. The file isn’t password protected. File system permissions limit access to your user account, so any process that runs as you can read it. Aspire doesn’t delete the file when you remove the call or the resource. Delete the file to discard the local credential.
  • Each run replaces all certificate credentials on the registration with the current certificate. Don’t add other certificates to a development registration, and restart sessions that use the old certificate after a renewal.
  • Referencing apps receive the certificate as a base64-encoded secret in ClientCredentials, with SourceType set to Base64Encoded. Base64 isn’t encryption, so don’t log the value.
  • The identity that provisions the registration needs the delegated Application.ReadWrite.All permission, or Application.ReadWrite.OwnedBy for a registration that it owns. For more information, see Required permissions.
  • Deleting the Azure resource group doesn’t delete the registration. For more information, see Clean up registrations.

For deployed apps, use a federated identity credential so that no secret is stored. The registration trusts a user-assigned managed identity, and the app authenticates as the registration by using that identity.

Create the trust for a registration that Aspire creates

Section titled “Create the trust for a registration that Aspire creates”

PublishWithFederatedManagedIdentityCredential makes the registration trust the managed identity of each app that references it.

apphost.mts
const entraWeb = await builder.addEntraIdApplication("entra-web")
.publishWithFederatedManagedIdentityCredential();
const web = await builder.addDotnetProject("web", "../Web/Web.csproj");
await web.withReference(entraWeb);

Referencing the registration makes the app need a user-assigned managed identity when published, the same way that referencing an Azure resource does. The app uses the identity it already has, for example from WithAzureUserAssignedIdentity. Otherwise the Azure environment creates one, which requires a compute environment that supports managed identities such as AddAzureContainerAppEnvironment.

For each trusted identity, Aspire adds a federated credential to the registration, and the app receives the identity’s client ID as ManagedIdentityClientId. Managed identity federation supports the Azure public, US Government, and China clouds.

Managed identities exist only in Azure, so this method has no effect when you run the AppHost. Use the local developer certificate or another credential for local development.

Pass a compute resource or a user-assigned identity to limit the trust. A compute resource that you pass must also reference the registration, and only that resource receives the credential.

apphost.mts
// Trust one app.
const entraWeb = await builder.addEntraIdApplication("entra-web");
const web = await builder.addDotnetProject("web", "../Web/Web.csproj");
await web.withReference(entraWeb);
await entraWeb.publishWithFederatedManagedIdentityCredential({ identity: web });
// Trust one explicit identity.
const identity = await builder.addAzureUserAssignedIdentity("web-identity");
const entraAdmin = await builder.addEntraIdApplication("entra-admin")
.publishWithFederatedManagedIdentityCredential({ identity });
const admin = await builder.addDotnetProject("admin", "../Admin/Admin.csproj");
await admin.withAzureUserAssignedIdentity(identity);
await admin.withReference(entraAdmin);

With an explicit identity, every app that references the registration must use that identity. Publishing fails with an error that names the app if a trusted app has no managed identity or doesn’t use the identity that the registration trusts.

The federated credential only changes how the app authenticates as itself. Interactive user sign-in still needs a redirect URI registered on the registration. Derive it from the web app’s endpoint with WithRedirectUris, which uses the compute environment’s host when deployed.

Use a managed identity trust that you created

Section titled “Use a managed identity trust that you created”

PublishWithFederatedManagedIdentityCredential throws for existing registrations. For those, create the trust yourself, then call WithFederatedManagedIdentityCredential with the managed identity’s client ID. This method only configures the app, and it applies when you run locally as well as when you publish.

apphost.mts
await entraWeb.withFederatedManagedIdentityCredential("00001111-aaaa-2222-bbbb-3333cccc4444");

Add a federated credential to the registration with these values. Otherwise, token requests fail with AADSTS700213.

  • Set the issuer to the tenant’s v2.0 endpoint, which is https://login.microsoftonline.com/{tenantId}/v2.0 in the Azure public cloud.
  • Set the subject to the identity’s principal ID, also called its object ID.
  • Set the audience to the token exchange audience of the cloud, which is api://AzureADTokenExchange in the Azure public cloud.

Pass the identity’s client ID, not its principal ID, to WithFederatedManagedIdentityCredential. In other clouds, also set the token exchange audience, and the token exchange authority if it differs from the app’s authority. In TypeScript, pass an options object such as { tokenExchangeUrl: "api://AzureADTokenExchangeUSGov" } that can also contain tokenExchangeAuthority. In C#, create an EntraIdFederatedIdentityCredential with the identity’s client ID, set its TokenExchangeUrl and TokenExchangeAuthority properties, and pass it to WithCredential instead. For more information, see Configure an application to trust a managed identity.

Federation authenticates as the app registration by using a managed identity assertion. To acquire a token directly as the managed identity instead, see Application roles.

WithClientSecret passes a secret parameter to the app. The parameter must be created as a secret.

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const tenantId = await builder.addParameter("entra-tenant-id");
const webClientId = await builder.addParameter("entra-web-client-id");
const webSecret = await builder.addParameter("entra-web-secret", { secret: true });
const entraWeb = await builder.addExistingEntraIdApplication("entra-web", tenantId, webClientId);
await entraWeb.withClientSecret(webSecret);
await builder.build().run();

Reference a Key Vault that you model in the AppHost instead of hard-coding its URL. This requires the Azure Key Vault hosting integration. This example continues the client secret example, which defines tenantId and webClientId.

apphost.mts
const vault = await builder.addAzureKeyVault("vault");
const entraWeb = await builder.addExistingEntraIdApplication("entra-web", tenantId, webClientId)
.withCertificateFromKeyVault(vault, "MyCert");
const web = await builder.addDotnetProject("web", "../Web/Web.csproj");
await web.withReference(entraWeb);

The certificate must already exist in the vault with an exportable private key, and its public key must already be registered on the Entra ID application. This helper doesn’t create the certificate or upload the public key. Microsoft.Identity.Web always retrieves the latest certificate version and has no setting to select a specific one.

Reading the certificate requires the Key Vault Certificate User role, which Aspire grants automatically when you pass a Key Vault resource:

  • When you run the AppHost, Aspire grants the role to your developer identity.
  • When you publish, Aspire grants the role to every app that references the Entra ID application. The publish target must support role assignments, such as AddAzureContainerAppEnvironment. Otherwise publishing fails with a “does not support role assignments” error.

To manage the roles yourself:

  • When you publish, call WithRoleAssignments for the vault on an app before it references the Entra ID application. Explicit assignments replace the automatic one, and an empty role list grants none.
  • When you run locally, call ClearDefaultRoleAssignments on the vault before WithCertificateFromKeyVault, and assign roles yourself.

For more information, see Azure role assignments.

You can model an existing vault with RunAsExisting or PublishAsExisting. Its access policies or RBAC configuration must allow certificate retrieval.

When the vault is managed outside the AppHost, pass its URL instead. Aspire grants no roles in this case, so configure access and identity yourself.

apphost.mts
await entraWeb.withCertificateFromKeyVault("https://myvault.vault.azure.net", "MyCert");

Use a thumbprint or a distinguished name to locate a certificate in the store on the machine that runs the app.

apphost.mts
await entraWeb.withCertificateThumbprint("CurrentUser/My", "ABC123...");
// Or locate the certificate by subject.
await entraWeb.withCertificateDistinguishedName("CurrentUser/My", "CN=MyCert");

The file paths identify files on the referencing app’s file system, not files that the AppHost reads. A certificate password must be a secret parameter. File credentials aren’t recommended for production.

apphost.mts
const certificatePassword = await builder.addParameter("certificate-password", { secret: true });
await entraWeb.withCertificateFromFile("/certs/client.pfx", { password: certificatePassword });
await entraWeb.withSignedAssertionFile({ filePath: "/tokens/assertion" });

Omit the file path of a signed assertion file to use the referencing app’s AZURE_FEDERATED_TOKEN_FILE setting. In C#, use WithCredential for credential types that don’t have a dedicated method.

WithSendX5C sends the x5c claim, which carries the public certificate, with token requests. Entra ID can then validate the certificate by subject name and issuer, which simplifies certificate rollover. This works only when the registration trusts the certificate’s subject name and issuer. Otherwise, Entra ID accepts only certificates registered on the application. WithSendX5C applies only to certificate-based credentials and increases the size of each token request, so it’s opt-in.

apphost.mts
await entraWeb.withSendX5C();