### AgentTokenService Setup and Usage (C#) Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/How-to-Use-FIC-and-FMI-in-Agentic-Scenarios Demonstrates the one-time setup and subsequent usage of the AgentTokenService for acquiring application and user tokens. This service manages the token acquisition flow for agents. ```csharp // --- One-time setup (application startup) --- X509Certificate2 cert = /* load your certificate */; var tokenService = new AgentTokenService( blueprintClientId: "YOUR_BLUEPRINT_CLIENT_ID", tenantId: "YOUR_TENANT_ID", cert); string[] graphScopes = { "https://graph.microsoft.com/.default" }; // --- App-only: agent gets a Graph token with no user context --- var appToken = await tokenService.AcquireAppTokenAsync("AGENT_APP_ID", graphScopes); // Use appToken.AccessToken for API calls // --- User flow (UPN): agent acts on behalf of a user --- var userToken = await tokenService.AcquireUserTokenAsync( "AGENT_APP_ID", graphScopes, "user@contoso.com"); // Use userToken.AccessToken for user-scoped API calls // --- User flow (OID): identify user by Object ID instead --- Guid userOid = new Guid("11111111-2222-3333-4444-555555555555"); var userTokenByOid = await tokenService.AcquireUserTokenAsync( "AGENT_APP_ID", graphScopes, userOid); // Store the identifier for later silent calls string accountId = userToken.Account.HomeAccountId.Identifier; // --- Subsequent requests: silent retrieval from cache --- var cached = await tokenService.AcquireUserTokenSilentAsync( "AGENT_APP_ID", graphScopes, accountId); ``` -------------------------------- ### Java - AgentTokenService Setup and Usage Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/How-to-Use-FIC-and-FMI-in-Agentic-Scenarios This Java code demonstrates the one-time setup for the AgentTokenService and how to acquire app-only and user-scoped tokens. It also shows how to silently retrieve cached tokens. ```java // --- One-time setup (application startup) --- PrivateKey privateKey = /* load your private key */; X509Certificate certificate = /* load your certificate */; AgentTokenService tokenService = new AgentTokenService( "YOUR_BLUEPRINT_CLIENT_ID", "YOUR_TENANT_ID", privateKey, certificate); Set graphScopes = Collections.singleton("https://graph.microsoft.com/.default"); // --- App-only: agent gets a Graph token with no user context --- IAuthenticationResult appToken = tokenService.acquireAppToken("AGENT_APP_ID", graphScopes); // Use appToken.accessToken() for API calls // --- User flow: agent acts on behalf of a user --- IAuthenticationResult userToken = tokenService.acquireUserToken( "AGENT_APP_ID", graphScopes, "user@contoso.com"); // Use userToken.accessToken() for user-scoped API calls // Store the identifier for later silent calls String accountId = userToken.account().homeAccountId(); // --- Subsequent requests: silent retrieval from cache --- IAuthenticationResult cached = tokenService.acquireUserTokenSilent( "AGENT_APP_ID", graphScopes, accountId); ``` -------------------------------- ### Install MSAL Packages for Token Binding Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/msi_v2/token-binding-demo.html This snippet shows the necessary NuGet packages to install for MSAL .NET to support token binding, including key attestation features. ```xml ``` -------------------------------- ### MSAL .NET Agentic Scenario Setup and Usage Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/How-to-Use-FIC-and-FMI-in-Agentic-Scenarios Demonstrates the one-time setup for an agent token service and subsequent calls to acquire application and user tokens. Includes silent token retrieval using cached account information. ```typescript import { readFileSync } from "fs"; // --- One-time setup (application startup) --- const privateKey = readFileSync("/path/to/cert.pem", "utf-8"); const tokenService = new AgentTokenService( "YOUR_BLUEPRINT_CLIENT_ID", "YOUR_TENANT_ID", privateKey, "YOUR_CERT_SHA256_THUMBPRINT" ); const graphScopes = ["https://graph.microsoft.com/.default"]; // --- App-only: agent gets a Graph token with no user context --- const appToken = await tokenService.acquireAppToken( "AGENT_APP_ID", graphScopes ); // Use appToken.accessToken for API calls // --- User flow (UPN): agent acts on behalf of a user --- const userToken = await tokenService.acquireUserToken( "AGENT_APP_ID", graphScopes, "user@contoso.com" ); // Use userToken.accessToken for user-scoped API calls // --- User flow (OID): identify user by Object ID instead --- const userTokenByOid = await tokenService.acquireUserTokenByObjectId( "AGENT_APP_ID", graphScopes, "11111111-2222-3333-4444-555555555555" ); // Store the account for later silent calls const account = userToken.account!; // --- Subsequent requests: silent retrieval from cache --- const cached = await tokenService.acquireUserTokenSilent( "AGENT_APP_ID", graphScopes, account ); ``` -------------------------------- ### Go AgentTokenService Usage Example Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/How-to-Use-FIC-and-FMI-in-Agentic-Scenarios Demonstrates how to initialize and use the AgentTokenService for acquiring different types of tokens. Ensure certificates are loaded correctly. ```go // Load certificate pemData, _ := os.ReadFile("/path/to/cert.pem") certs, key, _ := confidential.CertFromPEM(pemData, "") service := NewAgentTokenService("BLUEPRINT_CLIENT_ID", "YOUR_TENANT_ID", certs, key) ctx := context.Background() graphScopes := []string{"https://graph.microsoft.com/.default"} // --- App-only token --- result, _ := service.AcquireAppToken(ctx, "AGENT_APP_ID", graphScopes) // --- User-scoped token --- result, _ = service.AcquireUserToken(ctx, "AGENT_APP_ID", graphScopes, "user@contoso.com") // --- Subsequent requests: silent retrieval from cache --- cached, _ := service.AcquireUserTokenSilent(ctx, "AGENT_APP_ID", graphScopes, result.Account) ``` -------------------------------- ### IMDSv2 Metadata Request Example Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/mtlspop_managed_identity.md This is an example HTTP GET request to the Azure Instance Metadata Service (IMDS) v2 to retrieve platform metadata required for mTLS PoP. ```http GET http://169.254.169.254/metadata/identity/getplatformmetadata?cred-api-version=2.0 Header: Metadata: true ``` -------------------------------- ### Example Query for Xamarin iOS Issues Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/CONTRIBUTING.md An example GitHub issue query to filter for open issues specifically related to Xamarin iOS. ```html https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues?utf8=%E2%9C%93&q=is:issue+is:open+label:scenario:Mobile-iOS ``` -------------------------------- ### Install Token Binding Preview Packages Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/msi_v2/token-binding-demo.html These are the BETA/preview NuGet packages required for the token-binding Key Vault scenario. Ensure you are using the preview feed for these packages. ```xml ``` -------------------------------- ### Python AgentTokenService Usage Examples Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/How-to-Use-FIC-and-FMI-in-Agentic-Scenarios Demonstrates how to instantiate and use the AgentTokenService for acquiring app-only tokens, user-scoped tokens, and performing silent token retrievals. ```python service = AgentTokenService( blueprint_client_id="BLUEPRINT_CLIENT_ID", tenant_id="YOUR_TENANT_ID", cert_credential={ "private_key_pfx_path": "/path/to/cert.pfx", "public_certificate": True, }, ) graph_scopes = ["https://graph.microsoft.com/.default"] # --- App-only token --- result = service.acquire_app_token("AGENT_APP_ID", graph_scopes) # --- User-scoped token --- result = service.acquire_user_token( "AGENT_APP_ID", graph_scopes, "user@contoso.com") # --- Subsequent requests: silent retrieval from cache --- agent_app = service._get_agent_app("AGENT_APP_ID") accounts = agent_app.get_accounts() if accounts: cached = service.acquire_user_token_silent( "AGENT_APP_ID", graph_scopes, accounts[0]) ``` -------------------------------- ### Example Probe Request (PowerShell) Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/msi_v2/vm_vmss_credential_probe.md Use this PowerShell command to send a probe request to the MSI V2 /credential endpoint. Ensure to use the correct URI and method as specified. ```powershell Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/credential?cred-api-version=1.0' ` -Method POST ` -Body '.' ` -UseBasicParsing ``` -------------------------------- ### Clone and Test a Specific Pull Request Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/testing-prs-with-copilot.md A comprehensive example demonstrating how to clone a repository, fetch a specific pull request, check it out, and verify the current branch and latest commit. ```bash cd C:\code git clone https://github.com/AzureAD/microsoft-authentication-library-for-dotnet.git cd microsoft-authentication-library-for-dotnet git fetch origin pull/5733/head:pr/5733 git checkout pr/5733 code . git branch --show-current git log -1 --oneline ``` -------------------------------- ### Implement ICustomWebUI Interface Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released Example of implementing the ICustomWebUI interface for custom web UI integration in public client applications. This involves handling the AcquireAuthorizationCodeAsync method. ```CSharp public Task AcquireAuthorizationCodeAsync(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken) { // Implementation details for custom web UI interaction throw new NotImplementedException(); } ``` -------------------------------- ### Create Blueprint CCA with Certificate (Python) Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/How-to-Use-FIC-and-FMI-in-Agentic-Scenarios This Python example illustrates setting up a Blueprint CCA using MSAL. Setting `public_certificate: True` in the client credential configuration enables SNI (sending the x5c chain), which is necessary for FMI. ```python import msal blueprint_client_id = "YOUR_BLUEPRINT_CLIENT_ID" tenant_id = "YOUR_TENANT_ID" authority = f"https://login.microsoftonline.com/{tenant_id}" blueprint_app = msal.ConfidentialClientApplication( blueprint_client_id, client_credential={ "private_key_pfx_path": "/path/to/cert.pfx", "public_certificate": True, # enables SNI (send x5c chain) }, authority=authority, ) ``` -------------------------------- ### Restore and Run Sample Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/prototype/MsiWithSlc/readme.md Use these commands to restore dependencies and run the sample application. ```bash dotnet restore dotnet run --configuration Release ``` -------------------------------- ### Build and Run Demo App Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/prototype/MsiV2DemoApp/readme.md Commands to build the demo application in Release configuration and then run it. ```bash dotnet build -c Release dotnet run -c Release --project MsiV2DemoApp ``` -------------------------------- ### Checkout PR Branch (Example PR 5733) Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/testing-prs-with-copilot.md Fetch and checkout a specific pull request branch for testing, using PR 5733 as an example. ```bash git fetch origin pull/5733/head:pr/5733 git checkout pr/5733 ``` -------------------------------- ### Initialize PublicClientApplication with Telemetry Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/msal-net-4 Demonstrates how to create a PublicClientApplication and configure it with a telemetry configuration object. ```csharp var app = PublicClientApplication.Create(clientId) .WithTelemetry(telemetryConfig) .Build(); ``` -------------------------------- ### Build KeyGuardDemo Project Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/prototype/KeyGuardMaa/readme.md Clone the repository, restore NuGet packages from the internal feed, and build the managed wrapper and demo application in Release configuration. ```bash # Clone / copy the sources git clone https://.../KeyGuardDemo.git cd KeyGuardDemo # Restore packages from the **internal NuGet feed** dotnet restore # make sure your *NuGet.Config* points to the https://msazure.visualstudio.com/One/_artifacts/feed/Official/NuGet/Microsoft.Azure.Security.KeyGuardAttestation feed # Build the managed wrapper + demo dotnet build -c Release # Output ./bin/Release/net8.0/KeyGuardDemo.exe ``` -------------------------------- ### Create Public Client from Options Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released Build a public client application using configuration options loaded from a file or other source. ```CSharp PublicClientApplicationOptions = GetOptions(); // your own method. var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(options) .Build(); ``` -------------------------------- ### IMDSv2 Credential Issuance Request Example Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/mtlspop_managed_identity.md This is an example HTTP POST request to the IMDSv2 endpoint to issue a credential, which includes posting a Certificate Signing Request (CSR). The attestation_token is omitted if WithAttestationSupport() is not used. ```http POST http://169.254.169.254/metadata/identity/issuecredential?cred-api-version=2.0 Header: Metadata: true Body: { "csr": "", "attestation_token": "" } // attestation_token is omitted entirely when WithAttestationSupport() is not used ``` -------------------------------- ### Run KeyGuardDemo Application Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/prototype/KeyGuardMaa/readme.md Navigate to the build output directory and execute the KeyGuardDemo application to create a KeyGuard-protected key and obtain an attestation JWT. ```bash cd bin/Release/net8.0 KeyGuardDemo.exe ``` -------------------------------- ### MacMainThreadScheduler.Instance Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0-android/PublicAPI.Shipped.txt Gets the singleton instance of the MacMainThreadScheduler. ```APIDOC ## MacMainThreadScheduler.Instance ### Description Returns the singleton instance of the MacMainThreadScheduler, which is responsible for scheduling operations on the main thread of a macOS application. ### Method static ### Signature Microsoft.Identity.Client.Utils.MacMainThreadScheduler.Instance() -> Microsoft.Identity.Client.Utils.MacMainThreadScheduler ``` -------------------------------- ### TotalDurationInMs.get Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0-android/PublicAPI.Shipped.txt Gets the total duration in milliseconds. ```APIDOC ## TotalDurationInMs.get ### Description Retrieves the total duration of a metric or operation, measured in milliseconds. ### Method static ### Signature Microsoft.Identity.Client.Metrics.TotalDurationInMs.get -> long ``` -------------------------------- ### Kerberos.Credential.Current Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0/PublicAPI.Shipped.txt Gets the current Kerberos credential. ```APIDOC ## Kerberos.Credential.Current ### Description Retrieves the current Kerberos credential for the user. ### Method `static Credential Current()` ``` -------------------------------- ### Configuring SystemWebViewOptions for Interactive Token Acquisition Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/msal-net-4.1 Demonstrates how to configure SystemWebViewOptions to customize the user experience during interactive token acquisition using the system browser. ```CSharp IPublicClientApplication app; ... options = new SystemWebViewOptions { HtmlMessageError = "Sign-in failed. You can close this tab ...", BrowserRedirectSuccess = "https://contoso.com/help-for-my-awesome-commandline-tool.html" }; var result = app.AcquireTokenInteractive(scopes) .WithEmbeddedWebView(false) // The default in .NET Core .WithSystemWebViewOptions(options) .Build(); ``` -------------------------------- ### Entra STS Token Acquisition Request Example Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/mtlspop_managed_identity.md This is an example HTTP POST request to the regional Entra STS endpoint to acquire an access token using client credentials and mTLS. The binding certificate is used for the TLS client certificate during the handshake. ```http POST https://{region}.mtlsauth.microsoft.com/{tenantId}/oauth2/v2.0/token [TLS client certificate = binding certificate from step 4] Body: client_id = grant_type = client_credentials scope = https://management.azure.com/.default token_type = mtls_pop ← This is what makes it a PoP token ``` -------------------------------- ### Enable Broker Support in PublicClientApplicationBuilder Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-4.9.0-release-notes Use the `WithBroker()` configuration option when building a `PublicClientApplication` to enable broker support. This is recommended for a smoother sign-in experience and is required for conditional access scenarios. ```CSharp var app = PublicClientApplicationBuilder .Create(ClientId) .WithBroker() .WithRedirectUri(redirectUriOnAndroid) .Build(); ``` -------------------------------- ### Prompt.NoPrompt Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0-android/PublicAPI.Shipped.txt Gets a Prompt enum value representing no prompt. ```APIDOC ## Prompt.NoPrompt ### Description Represents the prompt behavior where no prompt is displayed to the user. ### Property static readonly Microsoft.Identity.Client.Prompt.NoPrompt -> Microsoft.Identity.Client.Prompt ``` -------------------------------- ### Prompt.Create Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0-android/PublicAPI.Shipped.txt Gets a Prompt enum value for creating a prompt. ```APIDOC ## Prompt.Create ### Description Represents the prompt behavior for creating a prompt. ### Property static readonly Microsoft.Identity.Client.Prompt.Create -> Microsoft.Identity.Client.Prompt ``` -------------------------------- ### Build Managed Identity Application and Acquire Token Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/msi_v2/proposal-capabilities-and-minstrength.md Demonstrates how to build a Managed Identity application, inspect its capabilities, and acquire a token with a minimum Proof of Possession strength requirement. Use this to ensure your service meets the necessary security binding. ```csharp var mi = ManagedIdentityApplicationBuilder .Create(ManagedIdentityId.SystemAssigned) .Build(); // 1. Inspect what this host can do (optional — for diagnostics / DefaultAzureCredential chain) var caps = await ((ManagedIdentityApplication)mi) .GetManagedIdentityCapabilitiesAsync(ct); if (caps.MaxSupportedBindingStrength < MtlsBindingStrength.KeyGuard) { logger.LogWarning("This host cannot meet KeyGuard requirement; service will refuse to start."); } // 2. Assert the floor when acquiring var result = await mi.AcquireTokenForManagedIdentity("https://vault.azure.net/.default") .WithMtlsProofOfPossession(new PoPOptions { MinStrength = MtlsBindingStrength.KeyGuard }) // throws if host can't deliver .ExecuteAsync(ct); ``` -------------------------------- ### Acquire Token Interactively (MSAL.NET 3.x) Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released Demonstrates the simplified and more readable builder pattern introduced in MSAL 3.x for acquiring tokens interactively, making it easier to specify accounts and extra scopes. ```CSharp var result = await app.AcquireTokenInteractive(scopesForCustomerApi) .WithAccount(accounts.FirstOrDefault()) .WithExtraScopesToConsent(scopesForVendorApi) .ExecuteAsync(); ``` -------------------------------- ### Prompt.Consent Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0-android/PublicAPI.Shipped.txt Gets a Prompt enum value representing consent. ```APIDOC ## Prompt.Consent ### Description Represents the prompt behavior for requesting user consent. ### Property static readonly Microsoft.Identity.Client.Prompt.Consent -> Microsoft.Identity.Client.Prompt ``` -------------------------------- ### MsalServiceException.SubErrorForLogging Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net462/PublicAPI.Shipped.txt Gets the sub-error code for logging purposes from an MsalServiceException. ```APIDOC ## MsalServiceException.SubErrorForLogging ### Description Gets the sub-error code for logging purposes from an MsalServiceException. ### Property get ### Returns string ``` -------------------------------- ### CacheOptions.EnableSharedCache Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net462/PublicAPI.Shipped.txt Gets cache options that enable the shared cache. ```APIDOC ## CacheOptions.EnableSharedCache ### Description Gets cache options that enable the shared cache. ### Method `static` ### Signature `Microsoft.Identity.Client.CacheOptions.EnableSharedCacheOptions.get -> Microsoft.Identity.Client.CacheOptions` ``` -------------------------------- ### CacheOptions.DisableInternalCache Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net462/PublicAPI.Shipped.txt Gets cache options that disable the internal cache. ```APIDOC ## CacheOptions.DisableInternalCache ### Description Gets cache options that disable the internal cache. ### Method `static` ### Signature `Microsoft.Identity.Client.CacheOptions.DisableInternalCacheOptions.get -> Microsoft.Identity.Client.CacheOptions` ``` -------------------------------- ### ManagedIdentityId.SystemAssigned Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net462/PublicAPI.Shipped.txt Gets a ManagedIdentityId representing the system-assigned managed identity. ```APIDOC ## ManagedIdentityId.SystemAssigned ### Description Gets a ManagedIdentityId representing the system-assigned managed identity. ### Method `static` ### Signature `Microsoft.Identity.Client.AppConfig.ManagedIdentityId.SystemAssigned.get -> Microsoft.Identity.Client.AppConfig.ManagedIdentityId` ``` -------------------------------- ### Prompt.SelectAccount Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0-android/PublicAPI.Shipped.txt Gets a Prompt enum value representing select account. ```APIDOC ## Prompt.SelectAccount ### Description Represents the prompt behavior for allowing the user to select an account. ### Property static readonly Microsoft.Identity.Client.Prompt.SelectAccount -> Microsoft.Identity.Client.Prompt ``` -------------------------------- ### Create Blueprint CCA with Certificate (Go) Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/How-to-Use-FIC-and-FMI-in-Agentic-Scenarios This Go snippet shows how to initialize a Blueprint CCA. The `confidential.WithX5C()` option is used to enable SNI, which is required for FMI flows. ```go import ( "crypto" "crypto/x509" "os" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" ) blueprintClientID := "YOUR_BLUEPRINT_CLIENT_ID" tenantID := "YOUR_TENANT_ID" authority := "https://login.microsoftonline.com/" + tenantID // Load certificate from PEM file pemData, _ := os.ReadFile("/path/to/cert.pem") certs, key, _ := confidential.CertFromPEM(pemData, "") cred, _ := confidential.NewCredFromCert(certs, key) // WithX5C() enables SNI (send x5c certificate chain) blueprintApp, _ := confidential.New(authority, blueprintClientID, cred, confidential.WithX5C()) ``` -------------------------------- ### Construct ConfidentialClientApplication Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-2.x-to-MSAL.NET-3.x Use ConfidentialClientApplicationBuilder.Create() or CreateWithOptions() for constructing ConfidentialClientApplication instances. ```csharp string clientId; ConfidentialClientApplicationOptions options; ``` ```csharp app=new ConfidentialClientApplication(clientId); ``` ```csharp app=ConfidentialClientApplicationBuilder .Create(clientId) .Build(); ``` ```csharp app=new ConfidentialClientApplication(clientId, authority); ``` ```csharp app=ConfidentialClientApplicationBuilder .Create(clientId) .WithAuthority(authority) .Build(); ``` ```csharp options = new ConfidentialClientApplicationOptions() { ClientId = client, Authority = authority }; app=ConfidentialClientApplicationBuilder .CreateWithOptions(options ) .Build(); ``` -------------------------------- ### Prompt.ForceLogin Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0-android/PublicAPI.Shipped.txt Gets a Prompt enum value representing force login. ```APIDOC ## Prompt.ForceLogin ### Description Represents the prompt behavior for forcing a user to log in again. ### Property static readonly Microsoft.Identity.Client.Prompt.ForceLogin -> Microsoft.Identity.Client.Prompt ``` -------------------------------- ### AbstractApplicationBuilder Configuration Methods Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0-ios/PublicAPI.Shipped.txt Methods for configuring application settings such as client ID, tenant ID, redirect URI, and other advanced options. ```APIDOC ## AbstractApplicationBuilder Configuration Methods ### Description Methods for configuring application settings such as client ID, tenant ID, redirect URI, and other advanced options. ### Methods - `WithClientCapabilities(IEnumerable clientCapabilities)`: Sets client capabilities. - `WithClientId(string clientId)`: Sets the application's client ID. - `WithExtraQueryParameters(string extraQueryParameters)`: Adds extra query parameters to the authentication request. - `WithExtraQueryParameters(IDictionary extraQueryParameters)`: Adds extra query parameters with cache key inclusion control. - `WithExtraQueryParameters(IDictionary extraQueryParameters)`: Adds extra query parameters as a dictionary. - `WithInstanceDiscoveryMetadata(string instanceDiscoveryJson)`: Configures instance discovery metadata from a JSON string. - `WithInstanceDiscoveryMetadata(Uri instanceDiscoveryUri)`: Configures instance discovery metadata from a URI. - `WithInstanceDiscovery(bool enableInstanceDiscovery)`: Enables or disables instance discovery. - `WithInstanceDiscoveryMetadata(string instanceDiscoveryJson)`: Configures instance discovery metadata from a JSON string (duplicate signature). - `WithInstanceDiscoveryMetadata(Uri instanceDiscoveryUri)`: Configures instance discovery metadata from a URI (duplicate signature). - `WithLegacyCacheCompatibility(bool enableLegacyCacheCompatibility = true)`: Enables legacy cache compatibility. - `WithRedirectUri(string redirectUri)`: Sets the redirect URI for the application. - `WithTelemetry(ITelemetryConfig telemetryConfig)`: Configures telemetry settings. ``` -------------------------------- ### Utils.MacMainThreadScheduler.Instance Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0/PublicAPI.Shipped.txt Gets the singleton instance of the Mac main thread scheduler. ```APIDOC ## MacMainThreadScheduler.Instance ### Description Provides access to the singleton instance of the main thread scheduler for macOS. ### Method `static MacMainThreadScheduler Instance()` ``` -------------------------------- ### MsalMetricsCatalog.CanonicalTagsByMetric Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net462/PublicAPI.Shipped.txt Gets a read-only dictionary of canonical tags by metric from the MsalMetricsCatalog. ```APIDOC ## MsalMetricsCatalog.CanonicalTagsByMetric ### Description Gets a read-only dictionary of canonical tags by metric from the MsalMetricsCatalog. ### Property static get ### Returns System.Collections.Generic.IReadOnlyDictionary> ``` -------------------------------- ### MSI V2 Token Acquisition Flow (Conceptual) Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/msi_v2/msi_with_credential_design.md Illustrates the conceptual steps involved in acquiring a token using MSI V2, from application request to receiving the token and certificate. ```mermaid sequenceDiagram participant App as Application participant MSAL participant IMDS participant MAA as Azureu MAA participant ESTS as Entrau STS (mTLS) App ->> MSAL: AcquireToken MSAL -> MSAL: Detect that MSIv2 is available, otherwise bail MSAL -> MSAL: Create the strongest key possible, e.g. in the TPM MSAL ->> MAA: Acquire an attestation token, which proves the key strength MSAL ->> IMDS: Certificate Signing Request with (key, attestation token) IMDS -->> MSAL: Certificate associated with key MSAL ->> ESTS: Open mTLS connection to ESTS with this certificate and acquire token ESTS -->> MSAL: token with special claim xms_tb MSAL -->> App: token and certificate ``` -------------------------------- ### PublicClientApplication.OperatingSystemAccount Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0/PublicAPI.Shipped.txt Gets the operating system account associated with the public client application. ```APIDOC ## OperatingSystemAccount ### Description Gets the `IAccount` representing the current operating system user. ### Property `static IAccount get` ``` -------------------------------- ### Open VS Code Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/testing-prs-with-copilot.md Open the current directory in Visual Studio Code. ```bash code . ``` -------------------------------- ### Get All Accounts Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net462/PublicAPI.Shipped.txt Retrieves all user accounts currently stored in the token cache. ```APIDOC ## GetAccountsAsync ### Description Retrieves all user accounts stored in the token cache asynchronously. This method is available on `IClientApplicationBase` and `IConfidentialClientApplication`. ### Method Signature (IClientApplicationBase) `Microsoft.Identity.Client.IClientApplicationBase.GetAccountsAsync()` ### Method Signature (IClientApplicationBase with userFlow) `Microsoft.Identity.Client.IClientApplicationBase.GetAccountsAsync(string userFlow)` ### Parameters (IClientApplicationBase with userFlow) * **userFlow** (`string`): An optional user flow identifier to filter accounts. ### Method Signature (IConfidentialClientApplication) `Microsoft.Identity.Client.IConfidentialClientApplication.GetAccountsAsync()` ### Returns `System.Threading.Tasks.Task>`: A task that represents the asynchronous operation, yielding a collection of accounts. ``` -------------------------------- ### SystemWebViewOptions Class Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0-ios/PublicAPI.Shipped.txt Options for configuring the system web browser. ```APIDOC ## SystemWebViewOptions Class ### Description Provides options for customizing the behavior of the system web browser used for authentication. ### Properties - **BrowserRedirectError** (`System.Uri`): The URI to redirect to in case of an error. - **BrowserRedirectSuccess** (`System.Uri`): The URI to redirect to upon successful authentication. - **HtmlMessageError** (`string`): Custom HTML message to display on error. - **HtmlMessageSuccess** (`string`): Custom HTML message to display on success. - **iOSHidePrivacyPrompt** (`bool`): Whether to hide the privacy prompt on iOS. - **OpenBrowserAsync** (`System.Func`): An asynchronous function to open the browser. ### Constructor #### SystemWebViewOptions() Initializes a new instance of the `SystemWebViewOptions` class with default values. ``` -------------------------------- ### Get Account Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net462/PublicAPI.Shipped.txt Retrieves a specific user account from the cache based on its identifier. ```APIDOC ## GetAccountAsync ### Description Retrieves a specific user account from the cache asynchronously. This method is part of the `IClientApplicationBase` interface. ### Method Signature `Microsoft.Identity.Client.IClientApplicationBase.GetAccountAsync(string identifier)` ### Parameters * **identifier** (`string`): The unique identifier of the account to retrieve. ### Returns `System.Threading.Tasks.Task`: A task that represents the asynchronous operation, yielding the found account or null if not found. ``` -------------------------------- ### Optional nuget.config Snippet Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/prototype/MsiV2DemoApp/readme.md An example configuration snippet to add the IDDP feed to your nuget.config file. ```xml ``` -------------------------------- ### ConfidentialClientApplication Methods Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0-ios/PublicAPI.Shipped.txt Methods for interacting with ConfidentialClientApplication, such as getting authorization request URLs and initiating long-running processes. ```APIDOC ## Microsoft.Identity.Client.ConfidentialClientApplication ### Description Provides methods for confidential clients to obtain security tokens. ### Methods #### GetAuthorizationRequestUrl Obtains the authorization request URL for confidential clients. - **scopes** (IEnumerable) - The scopes for which to request authorization. #### InitiateLongRunningProcessInWebApi Initiates a long-running process in a Web API. - **scopes** (IEnumerable) - The scopes for which to request authorization. - **userToken** (string) - The user token. - **longRunningProcessSessionKey** (ref string) - The session key for the long-running process. #### StopLongRunningProcessInWebApiAsync Stops a long-running process in a Web API. - **longRunningProcessSessionKey** (string) - The session key for the long-running process. - **cancellationToken** (CancellationToken) - The cancellation token. ### Returns - **GetAuthorizationRequestUrlParameterBuilder**: For GetAuthorizationRequestUrl. - **AcquireTokenOnBehalfOfParameterBuilder**: For InitiateLongRunningProcessInWebApi. - **Task**: For StopLongRunningProcessInWebApiAsync. ``` -------------------------------- ### Create Public Client Application (Minimal) Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released Instantiates a public client application with minimal configuration. By default, it targets Work and School Accounts and Microsoft personal accounts from the Azure public cloud. ```csharp IPublicClientApplication app; app = PublicClientApplicationBuilder.Create(clientId) .Build(); ``` -------------------------------- ### SystemWebViewOptions Class Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0-android/PublicAPI.Shipped.txt Options for configuring the system web view. ```APIDOC ## SystemWebViewOptions ### Description Provides options for customizing the behavior of the system web view used for authentication. ### Constructors - **SystemWebViewOptions()** - Description: Initializes a new instance of the `SystemWebViewOptions` class. ### Properties - **BrowserRedirectError** - Returns: `System.Uri` - Description: Gets or sets the URI to redirect to on browser error. - **BrowserRedirectSuccess** - Returns: `System.Uri` - Description: Gets or sets the URI to redirect to on browser success. - **HtmlMessageError** - Returns: `string` - Description: Gets or sets the HTML content to display on browser error. - **HtmlMessageSuccess** - Returns: `string` - Description: Gets or sets the HTML content to display on browser success. - **iOSHidePrivacyPrompt** - Returns: `bool` - Description: Gets or sets a value indicating whether to hide the privacy prompt on iOS. - **OpenBrowserAsync** - Returns: `System.Func` - Description: Gets or sets a function to asynchronously open the browser with a given URI. ``` -------------------------------- ### ILongRunningWebApi.InitiateLongRunningProcessInWebApi Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net472/PublicAPI.Shipped.txt Initiates a long-running process in a Web API. This method is used to start a process that requires a session key for tracking. ```APIDOC ## InitiateLongRunningProcessInWebApi ### Description Initiates a long-running process in a Web API. This method is used to start a process that requires a session key for tracking. ### Method Not applicable (SDK method) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example Not applicable (SDK method) ### Response #### Success Response Returns a `AcquireTokenOnBehalfOfParameterBuilder` which can be used to further configure the token acquisition. #### Response Example Not applicable (SDK method) ``` -------------------------------- ### JavaScript Initialization for Token Binding Demo Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/msi_v2/token-binding-demo.html Initializes the token binding simulation by setting up event listeners and rendering the initial state based on the selected mode. ```javascript const lane = host.querySelector('#simLane'); const tok = host.querySelector('#simTok'); const cap = host.querySelector('#simCap'); const logEl= host.querySelector('#simLog'); const dots = host.querySelector('#simDots'); const resEl= host.querySelector('#simResult'); const atkEl= host.querySelector('#simAttack'); const atkBox=host.querySelector('#simAtt'); let mode='bound', idx=-1, busy=false; function render(){ const d=SIM[mode]; lane.innerHTML = d.nodes.map(n=>'
'+n.t+'
'+n.s+'
').join(''); dots.innerHTML = d.steps.map(()=>'').join(''); logEl.innerHTML=''; idx=-1; tok.className='sim-token'; tok.textContent='\uD83C\uDF9F'; tok.style.opacity='0'; resEl.className='sim-result'; resEl.innerHTML=''; atkEl.className='sim-attack'; atkBox.style.display='none'; atkBox.textContent=''; cap.innerHTML='Press Play to mint a token \u2014 watch each hop call out, spin, and resolve. '; } ``` -------------------------------- ### PublicClientApplicationBuilder.Create Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net462/PublicAPI.Shipped.txt Creates a new instance of PublicClientApplicationBuilder with the specified client ID. This is the starting point for configuring a public client application. ```APIDOC ## PublicClientApplicationBuilder.Create ### Description Creates a new instance of PublicClientApplicationBuilder with the specified client ID. This is the starting point for configuring a public client application. ### Method static ### Signature static Microsoft.Identity.Client.PublicClientApplicationBuilder.Create(string clientId) -> Microsoft.Identity.Client.PublicClientApplicationBuilder ``` -------------------------------- ### ManagedIdentityApplicationBuilder.Create Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net462/PublicAPI.Shipped.txt Creates a builder for configuring a managed identity application. This is the starting point for creating an application instance that uses managed identity. ```APIDOC ## Create ### Description Creates a builder for configuring a managed identity application. This is the starting point for creating an application instance that uses managed identity. ### Method Static Method ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **ManagedIdentityApplicationBuilder** - A builder instance for configuring the managed identity application. #### Response Example None ``` -------------------------------- ### .NET Sample Dependency Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/prototype/MsiV2UsingPowerShell/readme.md Include this NuGet package in your .NET project when using the KeyGuard attestation package. Ensure the native DLL is deployed with your application. ```xml ``` -------------------------------- ### BaseAbstractApplicationBuilder Configuration Methods Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0/PublicAPI.Shipped.txt Methods for configuring application builders, including experimental features, HTTP client factories, and logging. ```APIDOC ## BaseAbstractApplicationBuilder Configuration Methods ### Description Methods for configuring application builders, including experimental features, HTTP client factories, and logging. ### Methods - `WithExperimentalFeatures(bool enableExperimentalFeatures = true)`: Enables or disables experimental features. - `WithHttpClientFactory(IMsalHttpClientFactory httpClientFactory, bool retryOnceOn5xx)`: Sets a custom HTTP client factory with retry logic for 5xx errors. - `WithHttpClientFactory(IMsalHttpClientFactory httpClientFactory)`: Sets a custom HTTP client factory. - `WithLogging(LogCallback loggingCallback, LogLevel? logLevel = null, bool? enablePiiLogging = null, bool? enableDefaultPlatformLogging = null)`: Configures logging with a callback, log level, and PII logging options. - `WithLogging(IIdentityLogger identityLogger, bool enablePiiLogging = false)`: Configures logging with an identity logger and PII logging option. ``` -------------------------------- ### ILongRunningWebApi.InitiateLongRunningProcessInWebApi Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net8.0/PublicAPI.Shipped.txt Initiates a long-running process in a web API. This method is used to start an asynchronous token acquisition flow that can be completed later. ```APIDOC ## InitiateLongRunningProcessInWebApi ### Description Initiates a long-running process in a web API. This method is used to start an asynchronous token acquisition flow that can be completed later. ### Method Not applicable (SDK method) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response Returns an `AcquireTokenOnBehalfOfParameterBuilder` object that can be used to configure and execute the token acquisition. It also outputs the `longRunningProcessSessionKey`. #### Response Example None ``` -------------------------------- ### Acquire Token by Username and Password (Simplified) Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/wiki/Username-Password-Authentication-2x This snippet demonstrates a basic implementation of acquiring an authentication token using the AcquireTokenByUsernamePasswordAsync method. It includes fetching accounts and conditionally acquiring a silent token or a new token via username/password. Ensure the 'clientId' is correctly configured. ```CSharp static async Task GetATokenForGraph() { string authority = "https://login.microsoftonline.com/contoso.com"; string[] scopes = new string[] { "user.read" }; PublicClientApplication app = new PublicClientApplication(clientId, authority); var accounts = await app.GetAccountsAsync(); AuthenticationResult result = null; if (accounts.Any()) { result = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault()); } else { try { var securePassword = new SecureString(); foreach (char c in "dummy") // you should fetch the password securePassword.AppendChar(c); // keystroke by keystroke result = await app.AcquireTokenByUsernamePasswordAsync(scopes, "joe@contoso.com", securePassword); } catch(MsalException) { // See details below } } Console.WriteLine(result.Account.Username); } ``` -------------------------------- ### Build MSAL.NET Package Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/CONTRIBUTING.md Use this command to create a package from the MSAL.NET project. Specify the custom version using the MicrosoftIdentityClientVersion parameter. ```bash msbuild .csproj /t:pack /p:MicrosoftIdentityClientVersion=1.2.3-preview ``` -------------------------------- ### Copilot Chat Skill Test Prompts Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/docs/testing-prs-with-copilot.md Examples of prompts to test specific GitHub Copilot skills related to MSAL and token acquisition. ```text Using the msal-mtls-pop-vanilla skill, show me how to acquire an mTLS PoP token with system-assigned managed identity (SAMI) for Microsoft Graph. ``` ```text Using the msal-mtls-pop-vanilla skill, show me how to acquire an mTLS PoP token with user-assigned managed identity using client ID 6325cd32-9911-41f3-819c-416cdf9104e7. ``` ```text Using the msal-mtls-pop-vanilla skill, show me how to acquire an mTLS PoP token with user-assigned managed identity using resource ID /subscriptions/c1686c51-b717-4fe0-9af3-24a20a41fb0c/resourcegroups/MSIV2-Testing-MSALNET/providers/Microsoft.ManagedIdentity/userAssignedIdentities/msiv2uami. ``` ```text Using the msal-mtls-pop-vanilla skill, show me how to acquire an mTLS PoP token with user-assigned managed identity using object ID ecb2ad92-3e30-4505-b79f-ac640d069f24. ``` ```text Using the msal-mtls-pop-vanilla skill, show me how to acquire an mTLS PoP token with a confidential client app using certificate-based authentication. ``` ```text Using the msal-mtls-pop-fic-two-leg skill, show me a two-leg token exchange where Leg 1 uses MSI to get a PoP token for api://AzureADTokenExchange, and Leg 2 uses a confidential client app to exchange that token for a Bearer token to Microsoft Graph. ``` ```text Using the msal-mtls-pop-fic-two-leg skill, show me a two-leg token exchange where Leg 1 uses MSI to get a PoP token for api://AzureADTokenExchange, and Leg 2 uses a confidential client app to exchange that token for an mTLS PoP token to Microsoft Graph. ``` ```text Using the msal-mtls-pop-fic-two-leg skill, show me a two-leg token exchange where both Leg 1 and Leg 2 use confidential client apps, with the final token being a Bearer token. ``` ```text Using the msal-mtls-pop-fic-two-leg skill, show me a two-leg token exchange where both legs use confidential client apps, with the final token being an mTLS PoP token. ``` ```text Using the msal-mtls-pop-guidance skill, what's the difference between vanilla and FIC flows? When should I use each? ``` -------------------------------- ### PublicClientApplicationBuilder.CreateWithApplicationOptions Source: https://github.com/azuread/microsoft-authentication-library-for-dotnet/blob/main/src/client/Microsoft.Identity.Client/PublicApi/net462/PublicAPI.Shipped.txt Creates a new instance of PublicClientApplicationBuilder using provided application options. This allows for more detailed configuration of the public client application. ```APIDOC ## PublicClientApplicationBuilder.CreateWithApplicationOptions ### Description Creates a new instance of PublicClientApplicationBuilder using provided application options. This allows for more detailed configuration of the public client application. ### Method static ### Signature static Microsoft.Identity.Client.PublicClientApplicationBuilder.CreateWithApplicationOptions(Microsoft.Identity.Client.PublicClientApplicationOptions options) -> Microsoft.Identity.Client.PublicClientApplicationBuilder ```