Commit iniziale

This commit is contained in:
Paolo A
2025-02-18 22:59:07 +00:00
commit 4bbf35cefb
6879 changed files with 623784 additions and 0 deletions

21
node_modules/@azure/identity/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

385
node_modules/@azure/identity/README.md generated vendored Normal file
View File

@@ -0,0 +1,385 @@
# Azure Identity client library for JavaScript
The Azure Identity library provides [Microsoft Entra ID](https://learn.microsoft.com/entra/fundamentals/whatis) ([formerly Azure Active Directory](https://learn.microsoft.com/entra/fundamentals/new-name)) token authentication through a set of convenient [TokenCredential](https://learn.microsoft.com/javascript/api/@azure/core-auth/tokencredential) implementations.
For examples of various credentials, see the [Azure Identity examples page](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md).
Key links:
- [Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity)
- [Package (npm)](https://www.npmjs.com/package/@azure/identity)
- [API Reference Documentation](https://learn.microsoft.com/javascript/api/@azure/identity)
- [Microsoft Entra ID documentation](https://learn.microsoft.com/entra/identity)
- [Samples](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples)
## Getting started
### Currently supported environments
- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule)
- Latest versions of Safari, Chrome, Edge, and Firefox.
- **Note**: Among the different credentials exported in this library, `InteractiveBrowserCredential` is the only one supported in the browser.
For more information, see our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md).
### Install the package
Install Azure Identity with `npm`:
```sh
npm install --save @azure/identity
```
### Prerequisites
- An [Azure subscription](https://azure.microsoft.com/free/).
- Optional: The [Azure CLI][azure_cli] and/or [Azure PowerShell][azure_powershell] can also be useful for authenticating in a development environment and managing account roles.
### When to use @azure/identity
The credential classes exposed by `@azure/identity` are focused on providing the most straightforward way to authenticate the Azure SDK clients locally, in your development environments, and in production. We aim for simplicity and reasonable support of the authentication protocols to cover most of the authentication scenarios possible on Azure. We're actively expanding to cover more scenarios. For a full list of the credentials offered, see the [Credential Classes](#credential-classes) section.
All credential types provided by `@azure/identity` are supported in Node.js. For browsers, `InteractiveBrowserCredential` is the credential type to be used for basic authentication scenarios.
Most of the credential types offered by `@azure/identity` use the [Microsoft Authentication Library for JavaScript (MSAL.js)](https://github.com/AzureAD/microsoft-authentication-library-for-js). Specifically, we use the v2 MSAL.js libraries, which use [OAuth 2.0 Authorization Code Flow with PKCE](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow) and are [OpenID-compliant](https://learn.microsoft.com/entra/identity-platform/v2-protocols-oidc). While `@azure/identity` focuses on simplicity, the MSAL.js libraries, such as [@azure/msal-common](https://www.npmjs.com/package/@azure/msal-common), [@azure/msal-node](https://www.npmjs.com/package/@azure/msal-node), and [@azure/msal-browser](https://www.npmjs.com/package/@azure/msal-browser), are designed to provide robust support for the authentication protocols that Azure supports.
#### When to use something else
The `@azure/identity` credential types are implementations of [@azure/core-auth](https://www.npmjs.com/package/@azure/core-auth)'s `TokenCredential` class. In principle, any object with a `getToken` method that satisfies `getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken | null>` works as a `TokenCredential`. This means developers can write their own credential types to support authentication cases not covered by `@azure/identity`. To learn more, see [Custom Credentials](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#custom-credentials).
Though our credential types support many advanced scenarios, developers may want to use [Microsoft Authentication Library for JavaScript (MSAL.js)](https://github.com/AzureAD/microsoft-authentication-library-for-js) directly instead. Consider using MSAL.js in the following scenarios:
- Developers who want full control of the authentication protocol and its configuration.
- Our credential types are designed to be used with Azure SDK clients with intelligent caching and token refreshing handled at the core HTTP layer. If you find yourself having to use `getToken` directly, you may benefit from using MSAL.js for more control over the authentication flow and token caching.
You can read more through the following links:
- We portray some advanced use cases of `@azure/identity` on the [Azure Identity Examples](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md) page.
- There, we specifically have an [Advanced Examples](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#advanced-examples) section.
- We also have a section that shows how to [Authenticate with MSAL directly](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-msal-directly).
For advanced authentication workflows in the browser, we have a section where we showcase how to use the [@azure/msal-browser](https://www.npmjs.com/package/@azure/msal-browser) library directly to authenticate Azure SDK clients.
### Authenticate the client in development environment
While we recommend using managed identity in your Azure-hosted application, it's typical for a developer to use their own account for authenticating calls to Azure services when debugging and executing code locally. There are several developer tools that can be used to perform this authentication in your development environment.
#### Authenticate via the Azure Developer CLI
Developers coding outside of an IDE can also use the [Azure Developer CLI][azure_developer_cli] to authenticate. Applications using the `DefaultAzureCredential` or the `AzureDeveloperCliCredential` can then use this account to authenticate calls in their application when running locally.
To authenticate with the [Azure Developer CLI][azure_developer_cli], users can run the command `azd auth login`. For users running on a system with a default web browser, the Azure Developer CLI launches the browser to authenticate the user.
For systems without a default web browser, the `azd auth login --use-device-code` command uses the device code authentication flow.
#### Authenticate via the Azure CLI
Applications using the `AzureCliCredential`, whether directly or via the `DefaultAzureCredential`, can use the Azure CLI account to authenticate calls in the application when running locally.
To authenticate with the [Azure CLI][azure_cli], run the command `az login`. For users running on a system with a default web browser, the Azure CLI launches the browser to authenticate the user.
![Azure CLI Account Sign In][azureclilogin_image]
For systems without a default web browser, the `az login` command uses the device code authentication flow. The user can also force the Azure CLI to use the device code flow rather than launching a browser by specifying the `--use-device-code` argument.
![Azure CLI Account Device Code Sign In][azureclilogindevicecode_image]
#### Authenticate via Azure PowerShell
Applications using the `AzurePowerShellCredential`, whether directly or via the `DefaultAzureCredential`, can use the account connected to Azure PowerShell to authenticate calls in the application when running locally.
To authenticate with [Azure PowerShell][azure_powershell], run the `Connect-AzAccount` cmdlet. By default, like the Azure CLI, `Connect-AzAccount` launches the default web browser to authenticate a user account.
![Azure PowerShell Account Sign In][azurepowershelllogin_image]
If interactive authentication can't be supported in the session, then the `-UseDeviceAuthentication` argument forces the cmdlet to use a device code authentication flow instead, similar to the corresponding option in the Azure CLI credential.
#### Authenticate via Visual Studio Code
Developers using Visual Studio Code can use the [Azure Account extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.azure-account) to authenticate via the editor. Apps using `VisualStudioCodeCredential` can then use this account to authenticate calls in their app when running locally.
To authenticate in Visual Studio Code, ensure the Azure Account extension is installed. Once installed, open the **Command Palette** and run the **Azure: Sign In** command.
Additionally, use the [`@azure/identity-vscode`](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity-vscode) plugin package. This package provides the dependencies of `VisualStudioCodeCredential` and enables it. See [Plugins](##plugins).
It's a [known issue](https://github.com/Azure/azure-sdk-for-js/issues/20500) that `VisualStudioCodeCredential` doesn't work with [Azure Account extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.azure-account) versions newer than **0.9.11**. A long-term fix to this problem is in progress. In the meantime, consider [authenticating via the Azure CLI](#authenticating-via-the-azure-cli).
### Authenticate the client in browsers
To authenticate Azure SDK clients within web browsers, we offer the `InteractiveBrowserCredential`, which can be set to use redirection or popups to complete the authentication flow. It's necessary to [create an Azure App Registration](https://learn.microsoft.com/entra/identity-platform/scenario-spa-app-registration) in the Azure portal for your web application first.
## Key concepts
If this is your first time using `@azure/identity` or Microsoft Entra ID, read [Using `@azure/identity` with Microsoft Entra ID](https://github.com/Azure/azure-sdk-for-js/blob/main/documentation/using-azure-identity.md) first. This document provides a deeper understanding of the platform and how to configure your Azure account correctly.
### Credentials
A credential is a class that contains or can obtain the data needed for a service client to authenticate requests. Service clients across the Azure SDK accept credentials when they're constructed. Service clients use those credentials to authenticate requests to the service.
The Azure Identity library focuses on OAuth authentication with Microsoft Entra ID, and it offers various credential classes capable of acquiring a Microsoft Entra token to authenticate service requests. All of the credential classes in this library are implementations of the [TokenCredential](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-auth/src/tokenCredential.ts) abstract class, and any of them can be used by to construct service clients capable of authenticating with a `TokenCredential`.
See [Credential Classes](#credential-classes).
### DefaultAzureCredential
`DefaultAzureCredential` simplifies authentication while developing apps that deploy to Azure by combining credentials used in Azure hosting environments with credentials used in local development. For more information, see [DefaultAzureCredential overview](https://aka.ms/azsdk/js/identity/credential-chains#use-defaultazurecredential-for-flexibility).
#### Continuation policy
As of version 3.3.0, `DefaultAzureCredential` attempts to authenticate with all developer credentials until one succeeds, regardless of any errors previous developer credentials experienced. For example, a developer credential may attempt to get a token and fail, so `DefaultAzureCredential` continues to the next credential in the flow. Deployed service credentials stop the flow with a thrown exception if they're able to attempt token retrieval, but don't receive one.
This allows for trying all of the developer credentials on your machine while having predictable deployed behavior.
#### Note about `VisualStudioCodeCredential`
Due to a [known issue](https://github.com/Azure/azure-sdk-for-js/issues/20500), `VisualStudioCodeCredential` has been removed from the `DefaultAzureCredential` token chain. When the issue is resolved in a future release, this change will be reverted.
## Plugins
Azure Identity for JavaScript provides a plugin API that allows us to provide certain functionality through separate _plugin packages_. The `@azure/identity` package exports a top-level function (`useIdentityPlugin`) that can be used to enable a plugin. We provide two plugin packages:
- [`@azure/identity-broker`](https://www.npmjs.com/package/@azure/identity-broker), which provides brokered authentication support through a native broker, such as Web Account Manager.
- [`@azure/identity-cache-persistence`](https://www.npmjs.com/package/@azure/identity-cache-persistence), which provides persistent token caching in Node.js using a native secure storage system provided by your operating system. This plugin allows cached `access_token` values to persist across sessions, meaning that an interactive login flow doesn't need to be repeated as long as a cached token is available.
## Examples
You can find more examples of using various credentials in [Azure Identity Examples Page](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md)
### Authenticate with `DefaultAzureCredential`
This example demonstrates authenticating the `KeyClient` from the [@azure/keyvault-keys](https://www.npmjs.com/package/@azure/keyvault-keys) client library using `DefaultAzureCredential`.
```ts snippet:defaultazurecredential_authenticate
import { DefaultAzureCredential } from "@azure/identity";
import { KeyClient } from "@azure/keyvault-keys";
// Configure vault URL
const vaultUrl = "https://<your-unique-keyvault-name>.vault.azure.net";
// Azure SDK clients accept the credential as a parameter
const credential = new DefaultAzureCredential();
// Create authenticated client
const client = new KeyClient(vaultUrl, credential);
```
### Specify a user-assigned managed identity with `DefaultAzureCredential`
A relatively common scenario involves authenticating using a user-assigned managed identity for an Azure resource. Explore the [example on Authenticating a user-assigned managed identity with DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-user-assigned-managed-identity-with-defaultazurecredential) to see how this is made a relatively straightforward task that can be configured using environment variables or in code.
### Define a custom authentication flow with `ChainedTokenCredential`
While `DefaultAzureCredential` is generally the quickest way to get started developing applications for Azure, more advanced users may want to customize the credentials considered when authenticating. The `ChainedTokenCredential` enables users to combine multiple credential instances to define a customized chain of credentials. This example demonstrates creating a `ChainedTokenCredential` that attempts to authenticate using two differently configured instances of `ClientSecretCredential`, to then authenticate the `KeyClient` from the [@azure/keyvault-keys](https://www.npmjs.com/package/@azure/keyvault-keys):
```ts snippet:chaintedtokencredential_authenticate
import { ClientSecretCredential, ChainedTokenCredential } from "@azure/identity";
import { KeyClient } from "@azure/keyvault-keys";
// Configure variables
const vaultUrl = "https://<your-unique-keyvault-name>.vault.azure.net";
const tenantId = "<tenant-id>";
const clientId = "<client-id>";
const clientSecret = "<client-secret>";
const anotherClientId = "<another-client-id>";
const anotherSecret = "<another-client-secret>";
// When an access token is requested, the chain will try each
// credential in order, stopping when one provides a token
const firstCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
const secondCredential = new ClientSecretCredential(tenantId, anotherClientId, anotherSecret);
const credentialChain = new ChainedTokenCredential(firstCredential, secondCredential);
// The chain can be used anywhere a credential is required
const client = new KeyClient(vaultUrl, credentialChain);
```
## Managed identity support
The [Managed identity authentication](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/overview) is supported via either the `DefaultAzureCredential` or the `ManagedIdentityCredential` credential classes directly for the following Azure services:
- [Azure App Service and Azure Functions](https://learn.microsoft.com/azure/app-service/overview-managed-identity)
- [Azure Arc](https://learn.microsoft.com/azure/azure-arc/servers/managed-identity-authentication)
- [Azure Cloud Shell](https://learn.microsoft.com/azure/cloud-shell/msi-authorization)
- [Azure Kubernetes Service](https://learn.microsoft.com/azure/aks/use-managed-identity)
- [Azure Service Fabric](https://learn.microsoft.com/azure/service-fabric/concepts-managed-identity)
- [Azure Virtual Machines](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/how-to-use-vm-token)
- [Azure Virtual Machines Scale Sets](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/qs-configure-powershell-windows-vmss)
For examples of how to use managed identity for authentication, see [the examples](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-in-azure-with-managed-identity).
## Cloud configuration
Credentials default to authenticating to the Microsoft Entra endpoint for Azure Public Cloud. To access resources in other clouds, such as Azure Government or a private cloud, configure credentials with the `authorityHost` argument in the constructor. The [`AzureAuthorityHosts`][authority_hosts] enum defines authorities for well-known clouds. For the US Government cloud, you could instantiate a credential this way:
```ts snippet:cloudconfiguration_authenticate
import { ClientSecretCredential, AzureAuthorityHosts } from "@azure/identity";
const credential = new ClientSecretCredential(
"<YOUR_TENANT_ID>",
"<YOUR_CLIENT_ID>",
"<YOUR_CLIENT_SECRET>",
{
authorityHost: AzureAuthorityHosts.AzureGovernment,
},
);
```
As an alternative to specifying the `authorityHost` argument, you can also set the `AZURE_AUTHORITY_HOST` environment variable to the URL of your cloud's authority. This approach is useful when configuring multiple credentials to authenticate to the same cloud or when the deployed environment needs to define the target cloud:
```sh
AZURE_AUTHORITY_HOST=https://login.partner.microsoftonline.cn
```
The `AzureAuthorityHosts` enum defines authorities for well-known clouds for your convenience; however, if the authority for your cloud isn't listed in `AzureAuthorityHosts`, you may pass any valid authority URL as a string argument. For example:
```ts snippet:cloudconfiguration_authorityhost
import { ClientSecretCredential } from "@azure/identity";
const credential = new ClientSecretCredential(
"<YOUR_TENANT_ID>",
"<YOUR_CLIENT_ID>",
"<YOUR_CLIENT_SECRET>",
{
authorityHost: "https://login.partner.microsoftonline.cn",
},
);
```
Not all credentials require this configuration. Credentials that authenticate through a development tool, such as `AzureCliCredential`, use that tool's configuration. Similarly, `VisualStudioCodeCredential` accepts an `authorityHost` argument but defaults to the `authorityHost` matching Visual Studio Code's **Azure: Cloud** setting.
## Credential classes
### Credential chains
| Credential | Usage | Example |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`DefaultAzureCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/defaultazurecredential?view=azure-node-latest) | Provides a simplified authentication experience to quickly start developing applications run in Azure. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-defaultazurecredential) |
| [`ChainedTokenCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/chainedtokencredential?view=azure-node-latest) | Allows users to define custom authentication flows composing multiple credentials. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#chaining-credentials) |
### Authenticate Azure-hosted applications
| Credential | Usage | Example |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`EnvironmentCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/environmentcredential?view=azure-node-latest) | Authenticates a service principal or user via credential information specified in environment variables. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-service-principal-with-environment-credentials) |
| [`ManagedIdentityCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/managedidentitycredential?view=azure-node-latest) | Authenticates the managed identity of an Azure resource. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-in-azure-with-managed-identity) |
| [`WorkloadIdentityCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/workloadidentitycredential?view=azure-node-latest) | Supports [Microsoft Entra Workload ID](https://learn.microsoft.com/azure/aks/workload-identity-overview) on Kubernetes. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-in-azure-with-workload-identity) |
| |
### Authenticate service principals
| Credential | Usage | Example | Reference |
| ---------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| [`AzurePipelinesCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/azurepipelinescredential?view=azure-node-latest) | Supports [Microsoft Entra Workload ID](https://learn.microsoft.com/azure/devops/pipelines/release/configure-workload-identity?view=azure-devops) on Azure Pipelines. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-in-azure-pipelines-with-service-connections) |
| [`ClientAssertionCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/clientassertioncredential?view=azure-node-latest) | Authenticates a service principal using a signed client assertion. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-service-principal-with-a-client-assertion) | [Service principal authentication](https://learn.microsoft.com/entra/identity-platform/app-objects-and-service-principals) |
| [`ClientCertificateCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/clientcertificatecredential?view=azure-node-latest) | Authenticates a service principal using a certificate. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-service-principal-with-a-client-certificate) | [Service principal authentication](https://learn.microsoft.com/entra/identity-platform/app-objects-and-service-principals) |
| [`ClientSecretCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/clientsecretcredential?view=azure-node-latest) | Authenticates a service principal using a secret. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-service-principal-with-a-client-secret) | [Service principal authentication](https://learn.microsoft.com/entra/identity-platform/app-objects-and-service-principals) |
### Authenticate users
| Credential | Usage | Example | Reference |
| ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| [`AuthorizationCodeCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/authorizationcodecredential?view=azure-node-latest) | Authenticates a user with a previously obtained authorization code. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-user-account-with-auth-code-flow) | [OAuth2 authentication code](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow) |
| [`DeviceCodeCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/devicecodecredential?view=azure-node-latest) | Interactively authenticates a user on devices with limited UI. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-user-account-with-device-code-flow) | [Device code authentication](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-device-code) |
| [`InteractiveBrowserCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/interactivebrowsercredential?view=azure-node-latest) | Interactively authenticates a user with the default system browser. Read more about how this happens [here](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/interactive-browser-credential.md). | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-user-account-interactively-in-the-browser) | [OAuth2 authentication code](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow) |
| [`OnBehalfOfCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/onbehalfofcredential?view=azure-node-latest) | Propagates the delegated user identity and permissions through the request chain | | [On-behalf-of authentication](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-on-behalf-of-flow) |
| [`UsernamePasswordCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/usernamepasswordcredential?view=azure-node-latest) | Authenticates a user with a username and password. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-user-account-with-username-and-password) | [Username + password authentication](https://learn.microsoft.com/entra/identity-platform/v2-oauth-ropc) |
### Authenticate via development tools
| Credential | Usage | Example | Reference |
| ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| [`AzureCliCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/azureclicredential?view=azure-node-latest) | Authenticate in a development environment with the Azure CLI. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-user-account-with-azure-cli) | [Azure CLI authentication](https://learn.microsoft.com/cli/azure/authenticate-azure-cli) |
| [`AzureDeveloperCliCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/azuredeveloperclicredential?view=azure-node-latest) | Authenticate in a development environment with the enabled user or service principal in Azure Developer CLI. | | [Azure Developer CLI Reference](https://learn.microsoft.com/azure/developer/azure-developer-cli/reference) |
| [`AzurePowerShellCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/azurepowershellcredential?view=azure-node-latest) | Authenticate in a development environment using Azure PowerShell. | [example](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-user-account-with-azure-powershell) | [Azure PowerShell authentication](https://learn.microsoft.com/powershell/azure/authenticate-azureps) |
| [`VisualStudioCodeCredential`](https://learn.microsoft.com/javascript/api/@azure/identity/visualstudiocodecredential?view=azure-node-latest) | Authenticates as the user signed in to the Visual Studio Code Azure Account extension. | | [VS Code Azure Account extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.azure-account) |
## Environment variables
`DefaultAzureCredential` and `EnvironmentCredential` can be configured with environment variables. Each type of authentication requires values for specific variables.
#### Service principal with secret
| Variable name | Value |
| --------------------- | ---------------------------------------------- |
| `AZURE_CLIENT_ID` | ID of a Microsoft Entra application |
| `AZURE_TENANT_ID` | ID of the application's Microsoft Entra tenant |
| `AZURE_CLIENT_SECRET` | one of the application's client secrets |
#### Service principal with certificate
| Variable name | Value |
|---------------------------------------|--------------------------------------------------------------|
| `AZURE_CLIENT_ID` | ID of a Microsoft Entra application |
| `AZURE_TENANT_ID` | ID of the application's Microsoft Entra tenant |
| `AZURE_CLIENT_CERTIFICATE_PATH` | path to a PEM-encoded certificate file including private key |
| `AZURE_CLIENT_CERTIFICATE_PASSWORD` | (optional) password of the certificate file, if any |
| `AZURE_CLIENT_SEND_CERTIFICATE_CHAIN` | (optional) send certificate chain in x5c header to support subject name / issuer-based authentication |
#### Username and password
| Variable name | Value |
| ----------------- | ---------------------------------------------- |
| `AZURE_CLIENT_ID` | ID of a Microsoft Entra application |
| `AZURE_TENANT_ID` | ID of the application's Microsoft Entra tenant |
| `AZURE_USERNAME` | a username (usually an email address) |
| `AZURE_PASSWORD` | that user's password |
Configuration is attempted in the preceding order. For example, if values for a client secret and certificate are both present, the client secret is used.
## Continuous Access Evaluation
As of version 3.3.0, accessing resources protected by [Continuous Access Evaluation](https://learn.microsoft.com/entra/identity/conditional-access/concept-continuous-access-evaluation) (CAE) is possible on a per-request basis. This can be enabled using the [`GetTokenOptions.enableCae(boolean)` API](https://learn.microsoft.com/javascript/api/@azure/core-auth/gettokenoptions?view=azure-node-latest#@azure-core-auth-gettokenoptions-enablecae). CAE isn't supported for developer credentials.
## Token caching
Token caching is a feature provided by the Azure Identity library that allows apps to:
- Cache tokens in memory (default) and on disk (opt-in).
- Improve resilience and performance.
- Reduce the number of requests made to Microsoft Entra ID to obtain access tokens.
The Azure Identity library offers both in-memory and persistent disk caching. For more information, see the [token caching documentation](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/TOKEN_CACHING.md).
## Brokered authentication
An authentication broker is an application that runs on a users machine and manages the authentication handshakes and token maintenance for connected accounts. Currently, only the Windows Web Account Manager (WAM) is supported. To enable support, use the [`@azure/identity-broker`][azure_identity_broker] package. For details on authenticating using WAM, see the [broker plugin documentation][azure_identity_broker_readme].
## Troubleshooting
For assistance with troubleshooting, see the [troubleshooting guide](https://aka.ms/azsdk/js/identity/troubleshoot).
## Next steps
### Read the documentation
API documentation for this library can be found on our [documentation site](https://learn.microsoft.com/javascript/api/@azure/identity).
### Client library support
Client and management libraries listed on the [Azure SDK releases page](https://azure.github.io/azure-sdk/releases/latest/js.html) that support Microsoft Entra authentication accept credentials from this library. Learn more about using these libraries in their documentation, which is linked from the releases page.
### Known issues
#### Azure AD B2C support
This library doesn't support the [Azure AD B2C](https://learn.microsoft.com/azure/active-directory-b2c/overview) service.
For other open issues, see the library's [GitHub repository](https://github.com/Azure/azure-sdk-for-js/issues?q=is%3Aopen+is%3Aissue+label%3AAzure.Identity).
### Provide feedback
If you encounter bugs or have suggestions, [open an issue](https://github.com/Azure/azure-sdk-for-js/issues).
## Contributing
To contribute to this library, read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code.
[azure_cli]: https://learn.microsoft.com/cli/azure
[azure_developer_cli]: https://learn.microsoft.com/azure/developer/azure-developer-cli
[azure_powershell]: https://learn.microsoft.com/powershell/azure/
[azureclilogin_image]: https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/identity/identity/images/AzureCliLogin.png
[azureclilogindevicecode_image]: https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/identity/identity/images/AzureCliLoginDeviceCode.png
[azurepowershelllogin_image]: https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/identity/identity/images/AzurePowerShellLogin.png
[defaultauthflow_image]: https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/identity/identity/images/mermaidjs/DefaultAzureCredentialAuthFlow.svg
[azure_identity_broker]: https://www.npmjs.com/package/@azure/identity-broker
[azure_identity_broker_readme]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity-broker
[authority_hosts]: https://learn.microsoft.com/javascript/api/@azure/identity/azureauthorityhosts
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fidentity%2Fidentity%2FREADME.png)

View File

@@ -0,0 +1,248 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { ServiceClient } from "@azure/core-client";
import { isNode } from "@azure/core-util";
import { createHttpHeaders, createPipelineRequest, } from "@azure/core-rest-pipeline";
import { AuthenticationError, AuthenticationErrorName } from "../errors";
import { getIdentityTokenEndpointSuffix } from "../util/identityTokenEndpoint";
import { DefaultAuthorityHost, SDK_VERSION } from "../constants";
import { tracingClient } from "../util/tracing";
import { logger } from "../util/logging";
import { parseExpirationTimestamp, parseRefreshTimestamp, } from "../credentials/managedIdentityCredential/utils";
const noCorrelationId = "noCorrelationId";
/**
* @internal
*/
export function getIdentityClientAuthorityHost(options) {
// The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable.
let authorityHost = options === null || options === void 0 ? void 0 : options.authorityHost;
// The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js.
if (isNode) {
authorityHost = authorityHost !== null && authorityHost !== void 0 ? authorityHost : process.env.AZURE_AUTHORITY_HOST;
}
// If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com
return authorityHost !== null && authorityHost !== void 0 ? authorityHost : DefaultAuthorityHost;
}
/**
* The network module used by the Identity credentials.
*
* It allows for credentials to abort any pending request independently of the MSAL flow,
* by calling to the `abortRequests()` method.
*
*/
export class IdentityClient extends ServiceClient {
constructor(options) {
var _a, _b;
const packageDetails = `azsdk-js-identity/${SDK_VERSION}`;
const userAgentPrefix = ((_a = options === null || options === void 0 ? void 0 : options.userAgentOptions) === null || _a === void 0 ? void 0 : _a.userAgentPrefix)
? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
: `${packageDetails}`;
const baseUri = getIdentityClientAuthorityHost(options);
if (!baseUri.startsWith("https:")) {
throw new Error("The authorityHost address must use the 'https' protocol.");
}
super(Object.assign(Object.assign({ requestContentType: "application/json; charset=utf-8", retryOptions: {
maxRetries: 3,
} }, options), { userAgentOptions: {
userAgentPrefix,
}, baseUri }));
this.allowInsecureConnection = false;
this.authorityHost = baseUri;
this.abortControllers = new Map();
this.allowLoggingAccountIdentifiers = (_b = options === null || options === void 0 ? void 0 : options.loggingOptions) === null || _b === void 0 ? void 0 : _b.allowLoggingAccountIdentifiers;
// used for WorkloadIdentity
this.tokenCredentialOptions = Object.assign({}, options);
// used for ManagedIdentity
if (options === null || options === void 0 ? void 0 : options.allowInsecureConnection) {
this.allowInsecureConnection = options.allowInsecureConnection;
}
}
async sendTokenRequest(request) {
logger.info(`IdentityClient: sending token request to [${request.url}]`);
const response = await this.sendRequest(request);
if (response.bodyAsText && (response.status === 200 || response.status === 201)) {
const parsedBody = JSON.parse(response.bodyAsText);
if (!parsedBody.access_token) {
return null;
}
this.logIdentifiers(response);
const token = {
accessToken: {
token: parsedBody.access_token,
expiresOnTimestamp: parseExpirationTimestamp(parsedBody),
refreshAfterTimestamp: parseRefreshTimestamp(parsedBody),
tokenType: "Bearer",
},
refreshToken: parsedBody.refresh_token,
};
logger.info(`IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`);
return token;
}
else {
const error = new AuthenticationError(response.status, response.bodyAsText);
logger.warning(`IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`);
throw error;
}
}
async refreshAccessToken(tenantId, clientId, scopes, refreshToken, clientSecret, options = {}) {
if (refreshToken === undefined) {
return null;
}
logger.info(`IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`);
const refreshParams = {
grant_type: "refresh_token",
client_id: clientId,
refresh_token: refreshToken,
scope: scopes,
};
if (clientSecret !== undefined) {
refreshParams.client_secret = clientSecret;
}
const query = new URLSearchParams(refreshParams);
return tracingClient.withSpan("IdentityClient.refreshAccessToken", options, async (updatedOptions) => {
try {
const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);
const request = createPipelineRequest({
url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,
method: "POST",
body: query.toString(),
abortSignal: options.abortSignal,
headers: createHttpHeaders({
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
}),
tracingOptions: updatedOptions.tracingOptions,
});
const response = await this.sendTokenRequest(request);
logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);
return response;
}
catch (err) {
if (err.name === AuthenticationErrorName &&
err.errorResponse.error === "interaction_required") {
// It's likely that the refresh token has expired, so
// return null so that the credential implementation will
// initiate the authentication flow again.
logger.info(`IdentityClient: interaction required for client ID: ${clientId}`);
return null;
}
else {
logger.warning(`IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`);
throw err;
}
}
});
}
// Here is a custom layer that allows us to abort requests that go through MSAL,
// since MSAL doesn't allow us to pass options all the way through.
generateAbortSignal(correlationId) {
const controller = new AbortController();
const controllers = this.abortControllers.get(correlationId) || [];
controllers.push(controller);
this.abortControllers.set(correlationId, controllers);
const existingOnAbort = controller.signal.onabort;
controller.signal.onabort = (...params) => {
this.abortControllers.set(correlationId, undefined);
if (existingOnAbort) {
existingOnAbort.apply(controller.signal, params);
}
};
return controller.signal;
}
abortRequests(correlationId) {
const key = correlationId || noCorrelationId;
const controllers = [
...(this.abortControllers.get(key) || []),
// MSAL passes no correlation ID to the get requests...
...(this.abortControllers.get(noCorrelationId) || []),
];
if (!controllers.length) {
return;
}
for (const controller of controllers) {
controller.abort();
}
this.abortControllers.set(key, undefined);
}
getCorrelationId(options) {
var _a;
const parameter = (_a = options === null || options === void 0 ? void 0 : options.body) === null || _a === void 0 ? void 0 : _a.split("&").map((part) => part.split("=")).find(([key]) => key === "client-request-id");
return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId;
}
// The MSAL network module methods follow
async sendGetRequestAsync(url, options) {
const request = createPipelineRequest({
url,
method: "GET",
body: options === null || options === void 0 ? void 0 : options.body,
allowInsecureConnection: this.allowInsecureConnection,
headers: createHttpHeaders(options === null || options === void 0 ? void 0 : options.headers),
abortSignal: this.generateAbortSignal(noCorrelationId),
});
const response = await this.sendRequest(request);
this.logIdentifiers(response);
return {
body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,
headers: response.headers.toJSON(),
status: response.status,
};
}
async sendPostRequestAsync(url, options) {
const request = createPipelineRequest({
url,
method: "POST",
body: options === null || options === void 0 ? void 0 : options.body,
headers: createHttpHeaders(options === null || options === void 0 ? void 0 : options.headers),
allowInsecureConnection: this.allowInsecureConnection,
// MSAL doesn't send the correlation ID on the get requests.
abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),
});
const response = await this.sendRequest(request);
this.logIdentifiers(response);
return {
body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,
headers: response.headers.toJSON(),
status: response.status,
};
}
/**
*
* @internal
*/
getTokenCredentialOptions() {
return this.tokenCredentialOptions;
}
/**
* If allowLoggingAccountIdentifiers was set on the constructor options
* we try to log the account identifiers by parsing the received access token.
*
* The account identifiers we try to log are:
* - `appid`: The application or Client Identifier.
* - `upn`: User Principal Name.
* - It might not be available in some authentication scenarios.
* - If it's not available, we put a placeholder: "No User Principal Name available".
* - `tid`: Tenant Identifier.
* - `oid`: Object Identifier of the authenticated user.
*/
logIdentifiers(response) {
if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) {
return;
}
const unavailableUpn = "No User Principal Name available";
try {
const parsed = response.parsedBody || JSON.parse(response.bodyAsText);
const accessToken = parsed.access_token;
if (!accessToken) {
// Without an access token allowLoggingAccountIdentifiers isn't useful.
return;
}
const base64Metadata = accessToken.split(".")[1];
const { appid, upn, tid, oid } = JSON.parse(Buffer.from(base64Metadata, "base64").toString("utf8"));
logger.info(`[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${upn || unavailableUpn}. Object ID (user): ${oid}`);
}
catch (e) {
logger.warning("allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:", e.message);
}
}
}
//# sourceMappingURL=identityClient.js.map

File diff suppressed because one or more lines are too long

67
node_modules/@azure/identity/dist-esm/src/constants.js generated vendored Normal file
View File

@@ -0,0 +1,67 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* Current version of the `@azure/identity` package.
*/
export const SDK_VERSION = `4.6.0`;
/**
* The default client ID for authentication
* @internal
*/
// TODO: temporary - this is the Azure CLI clientID - we'll replace it when
// Developer Sign On application is available
// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9
export const DeveloperSignOnClientId = "04b07795-8ddb-461a-bbee-02f9e1bf7b46";
/**
* The default tenant for authentication
* @internal
*/
export const DefaultTenantId = "common";
/**
* A list of known Azure authority hosts
*/
export var AzureAuthorityHosts;
(function (AzureAuthorityHosts) {
/**
* China-based Azure Authority Host
*/
AzureAuthorityHosts["AzureChina"] = "https://login.chinacloudapi.cn";
/**
* Germany-based Azure Authority Host
*/
AzureAuthorityHosts["AzureGermany"] = "https://login.microsoftonline.de";
/**
* US Government Azure Authority Host
*/
AzureAuthorityHosts["AzureGovernment"] = "https://login.microsoftonline.us";
/**
* Public Cloud Azure Authority Host
*/
AzureAuthorityHosts["AzurePublicCloud"] = "https://login.microsoftonline.com";
})(AzureAuthorityHosts || (AzureAuthorityHosts = {}));
/**
* @internal
* The default authority host.
*/
export const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud;
/**
* @internal
* Allow acquiring tokens for any tenant for multi-tentant auth.
*/
export const ALL_TENANTS = ["*"];
/**
* @internal
*/
export const CACHE_CAE_SUFFIX = "cae";
/**
* @internal
*/
export const CACHE_NON_CAE_SUFFIX = "nocae";
/**
* @internal
*
* The default name for the cache persistence plugin.
* Matches the constant defined in the cache persistence package.
*/
export const DEFAULT_TOKEN_CACHE_NAME = "msal.cache";
//# sourceMappingURL=constants.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC;AAEnC;;;GAGG;AACH,2EAA2E;AAC3E,6CAA6C;AAC7C,uGAAuG;AACvG,MAAM,CAAC,MAAM,uBAAuB,GAAG,sCAAsC,CAAC;AAE9E;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC;AAExC;;GAEG;AACH,MAAM,CAAN,IAAY,mBAiBX;AAjBD,WAAY,mBAAmB;IAC7B;;OAEG;IACH,oEAA6C,CAAA;IAC7C;;OAEG;IACH,wEAAiD,CAAA;IACjD;;OAEG;IACH,2EAAoD,CAAA;IACpD;;OAEG;IACH,6EAAsD,CAAA;AACxD,CAAC,EAjBW,mBAAmB,KAAnB,mBAAmB,QAiB9B;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,mBAAmB,CAAC,gBAAgB,CAAC;AAEzE;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAa,CAAC,GAAG,CAAC,CAAC;AAE3C;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAEtC;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,YAAY,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Current version of the `@azure/identity` package.\n */\nexport const SDK_VERSION = `4.6.0`;\n\n/**\n * The default client ID for authentication\n * @internal\n */\n// TODO: temporary - this is the Azure CLI clientID - we'll replace it when\n// Developer Sign On application is available\n// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9\nexport const DeveloperSignOnClientId = \"04b07795-8ddb-461a-bbee-02f9e1bf7b46\";\n\n/**\n * The default tenant for authentication\n * @internal\n */\nexport const DefaultTenantId = \"common\";\n\n/**\n * A list of known Azure authority hosts\n */\nexport enum AzureAuthorityHosts {\n /**\n * China-based Azure Authority Host\n */\n AzureChina = \"https://login.chinacloudapi.cn\",\n /**\n * Germany-based Azure Authority Host\n */\n AzureGermany = \"https://login.microsoftonline.de\",\n /**\n * US Government Azure Authority Host\n */\n AzureGovernment = \"https://login.microsoftonline.us\",\n /**\n * Public Cloud Azure Authority Host\n */\n AzurePublicCloud = \"https://login.microsoftonline.com\",\n}\n\n/**\n * @internal\n * The default authority host.\n */\nexport const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud;\n\n/**\n * @internal\n * Allow acquiring tokens for any tenant for multi-tentant auth.\n */\nexport const ALL_TENANTS: string[] = [\"*\"];\n\n/**\n * @internal\n */\nexport const CACHE_CAE_SUFFIX = \"cae\";\n\n/**\n * @internal\n */\nexport const CACHE_NON_CAE_SUFFIX = \"nocae\";\n\n/**\n * @internal\n *\n * The default name for the cache persistence plugin.\n * Matches the constant defined in the cache persistence package.\n */\nexport const DEFAULT_TOKEN_CACHE_NAME = \"msal.cache\";\n"]}

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=authorityValidationOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"authorityValidationOptions.js","sourceRoot":"","sources":["../../../src/credentials/authorityValidationOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Provides options to configure how the Identity library\n * does authority validation during authentication requests\n * to Microsoft Entra ID.\n */\nexport interface AuthorityValidationOptions {\n /**\n * The field determines whether instance discovery is performed when attempting to authenticate.\n * Setting this to `true` will completely disable both instance discovery and authority validation.\n * As a result, it's crucial to ensure that the configured authority host is valid and trustworthy.\n * This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in private clouds or Azure Stack.\n * The process of instance discovery entails retrieving authority metadata from https://login.microsoft.com/ to validate the authority.\n */\n disableInstanceDiscovery?: boolean;\n}\n"]}

View File

@@ -0,0 +1,16 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
const BrowserNotSupportedError = new Error("AuthorizationCodeCredential is not supported in the browser. InteractiveBrowserCredential is more appropriate for this use case.");
const logger = credentialLogger("AuthorizationCodeCredential");
export class AuthorizationCodeCredential {
constructor() {
logger.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
getToken() {
logger.getToken.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
}
//# sourceMappingURL=authorizationCodeCredential.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"authorizationCodeCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/authorizationCodeCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,kIAAkI,CACnI,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,6BAA6B,CAAC,CAAC;AAE/D,MAAM,OAAO,2BAA2B;IAmBtC;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,QAAQ;QACb,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError } from \"../util/logging\";\nimport { AuthorizationCodeCredentialOptions } from \"./authorizationCodeCredentialOptions\";\n\nconst BrowserNotSupportedError = new Error(\n \"AuthorizationCodeCredential is not supported in the browser. InteractiveBrowserCredential is more appropriate for this use case.\",\n);\nconst logger = credentialLogger(\"AuthorizationCodeCredential\");\n\nexport class AuthorizationCodeCredential implements TokenCredential {\n /**\n * Only available in Node.js\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n clientSecret: string,\n authorizationCode: string,\n redirectUri: string,\n options?: AuthorizationCodeCredentialOptions,\n );\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n authorizationCode: string,\n redirectUri: string,\n options?: AuthorizationCodeCredentialOptions,\n );\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}

View File

@@ -0,0 +1,60 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
import { checkTenantId } from "../util/tenantIdUtils";
import { credentialLogger } from "../util/logging";
import { ensureScopes } from "../util/scopeUtils";
import { tracingClient } from "../util/tracing";
import { createMsalClient } from "../msal/nodeFlows/msalClient";
const logger = credentialLogger("AuthorizationCodeCredential");
/**
* Enables authentication to Microsoft Entra ID using an authorization code
* that was obtained through the authorization code flow, described in more detail
* in the Microsoft Entra ID documentation:
*
* https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow
*/
export class AuthorizationCodeCredential {
/**
* @hidden
* @internal
*/
constructor(tenantId, clientId, clientSecretOrAuthorizationCode, authorizationCodeOrRedirectUri, redirectUriOrOptions, options) {
checkTenantId(logger, tenantId);
this.clientSecret = clientSecretOrAuthorizationCode;
if (typeof redirectUriOrOptions === "string") {
// the clientId+clientSecret constructor
this.authorizationCode = authorizationCodeOrRedirectUri;
this.redirectUri = redirectUriOrOptions;
// in this case, options are good as they come
}
else {
// clientId only
this.authorizationCode = clientSecretOrAuthorizationCode;
this.redirectUri = authorizationCodeOrRedirectUri;
this.clientSecret = undefined;
options = redirectUriOrOptions;
}
// TODO: Validate tenant if provided
this.tenantId = tenantId;
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options !== null && options !== void 0 ? options : {} }));
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(scopes, options = {}) {
return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
const tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds);
newOptions.tenantId = tenantId;
const arrayScopes = ensureScopes(scopes);
return this.msalClient.getTokenByAuthorizationCode(arrayScopes, this.redirectUri, this.authorizationCode, this.clientSecret, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication }));
});
}
}
//# sourceMappingURL=authorizationCodeCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=authorizationCodeCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"authorizationCodeCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/authorizationCodeCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AuthorityValidationOptions } from \"./authorityValidationOptions\";\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Options for the {@link AuthorizationCodeCredential}\n */\nexport interface AuthorizationCodeCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n AuthorityValidationOptions {}\n"]}

View File

@@ -0,0 +1,34 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
import { ChainedTokenCredential } from "./chainedTokenCredential";
const BrowserNotSupportedError = new Error("ApplicationCredential is not supported in the browser. Use InteractiveBrowserCredential instead.");
const logger = credentialLogger("ApplicationCredential");
/**
* Provides a default {@link ChainedTokenCredential} configuration for
* applications that will be deployed to Azure.
*
* Only available in Node.js
*/
export class AzureApplicationCredential extends ChainedTokenCredential {
/**
* Creates an instance of the AzureApplicationCredential class.
*
* The AzureApplicationCredential provides a default {@link ChainedTokenCredential} configuration for
* applications that will be deployed to Azure.
*
* Only available in Node.js
*
* @param options - Options for configuring the client which makes the authentication request.
*/
constructor(_tokenCredentialOptions) {
super();
logger.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
getToken() {
logger.getToken.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
}
//# sourceMappingURL=azureApplicationCredential.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"azureApplicationCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/azureApplicationCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAGlE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,kGAAkG,CACnG,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,uBAAuB,CAAC,CAAC;AAEzD;;;;;GAKG;AACH,MAAM,OAAO,0BAA2B,SAAQ,sBAAsB;IACpE;;;;;;;;;OASG;IACH,YAAY,uBAAgD;QAC1D,KAAK,EAAE,CAAC;QACR,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,QAAQ;QACb,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { credentialLogger, formatError } from \"../util/logging\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { ChainedTokenCredential } from \"./chainedTokenCredential\";\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\n\nconst BrowserNotSupportedError = new Error(\n \"ApplicationCredential is not supported in the browser. Use InteractiveBrowserCredential instead.\",\n);\nconst logger = credentialLogger(\"ApplicationCredential\");\n\n/**\n * Provides a default {@link ChainedTokenCredential} configuration for\n * applications that will be deployed to Azure.\n *\n * Only available in Node.js\n */\nexport class AzureApplicationCredential extends ChainedTokenCredential {\n /**\n * Creates an instance of the AzureApplicationCredential class.\n *\n * The AzureApplicationCredential provides a default {@link ChainedTokenCredential} configuration for\n * applications that will be deployed to Azure.\n *\n * Only available in Node.js\n *\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(_tokenCredentialOptions?: TokenCredentialOptions) {\n super();\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public getToken(): Promise<AccessToken> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}

View File

@@ -0,0 +1,32 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createDefaultManagedIdentityCredential, createEnvironmentCredential, } from "./defaultAzureCredential";
import { ChainedTokenCredential } from "./chainedTokenCredential";
/**
* Provides a default {@link ChainedTokenCredential} configuration that should
* work for most applications that use the Azure SDK.
*/
export class AzureApplicationCredential extends ChainedTokenCredential {
/**
* Creates an instance of the AzureApplicationCredential class.
*
* The AzureApplicationCredential provides a default {@link ChainedTokenCredential} configuration that should
* work for most applications deployed on Azure. The following credential types will be tried, in order:
*
* - {@link EnvironmentCredential}
* - {@link ManagedIdentityCredential}
*
* Consult the documentation of these credential types for more information
* on how they attempt authentication.
*
* @param options - Optional parameters. See {@link AzureApplicationCredentialOptions}.
*/
constructor(options) {
const credentialFunctions = [
createEnvironmentCredential,
createDefaultManagedIdentityCredential,
];
super(...credentialFunctions.map((createCredentialFn) => createCredentialFn(options)));
}
}
//# sourceMappingURL=azureApplicationCredential.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"azureApplicationCredential.js","sourceRoot":"","sources":["../../../src/credentials/azureApplicationCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,sCAAsC,EACtC,2BAA2B,GAC5B,MAAM,0BAA0B,CAAC;AAGlC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAElE;;;GAGG;AACH,MAAM,OAAO,0BAA2B,SAAQ,sBAAsB;IACpE;;;;;;;;;;;;;OAaG;IACH,YAAY,OAA2C;QACrD,MAAM,mBAAmB,GAAG;YAC1B,2BAA2B;YAC3B,sCAAsC;SACvC,CAAC;QACF,KAAK,CAAC,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC,kBAAkB,EAAE,EAAE,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IACzF,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport {\n createDefaultManagedIdentityCredential,\n createEnvironmentCredential,\n} from \"./defaultAzureCredential\";\n\nimport { AzureApplicationCredentialOptions } from \"./azureApplicationCredentialOptions\";\nimport { ChainedTokenCredential } from \"./chainedTokenCredential\";\n\n/**\n * Provides a default {@link ChainedTokenCredential} configuration that should\n * work for most applications that use the Azure SDK.\n */\nexport class AzureApplicationCredential extends ChainedTokenCredential {\n /**\n * Creates an instance of the AzureApplicationCredential class.\n *\n * The AzureApplicationCredential provides a default {@link ChainedTokenCredential} configuration that should\n * work for most applications deployed on Azure. The following credential types will be tried, in order:\n *\n * - {@link EnvironmentCredential}\n * - {@link ManagedIdentityCredential}\n *\n * Consult the documentation of these credential types for more information\n * on how they attempt authentication.\n *\n * @param options - Optional parameters. See {@link AzureApplicationCredentialOptions}.\n */\n constructor(options?: AzureApplicationCredentialOptions) {\n const credentialFunctions = [\n createEnvironmentCredential,\n createDefaultManagedIdentityCredential,\n ];\n super(...credentialFunctions.map((createCredentialFn) => createCredentialFn(options)));\n }\n}\n"]}

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=azureApplicationCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"azureApplicationCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/azureApplicationCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Provides options to configure the {@link AzureApplicationCredential} class.\n */\nexport interface AzureApplicationCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n CredentialPersistenceOptions {\n /**\n * Optionally pass in a user assigned client ID to be used by the {@link ManagedIdentityCredential}.\n * This client ID can also be passed through to the {@link ManagedIdentityCredential} through the environment variable: AZURE_CLIENT_ID.\n */\n managedIdentityClientId?: string;\n}\n"]}

View File

@@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
const BrowserNotSupportedError = new Error("AzureCliCredential is not supported in the browser.");
const logger = credentialLogger("AzureCliCredential");
/**
* This credential will use the currently logged-in user login information
* via the Azure CLI ('az') commandline tool.
*/
export class AzureCliCredential {
/**
* Only available in Node.js
*/
constructor() {
logger.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
getToken() {
logger.getToken.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
}
//# sourceMappingURL=azureCliCredential.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"azureCliCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/azureCliCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;AAClG,MAAM,MAAM,GAAG,gBAAgB,CAAC,oBAAoB,CAAC,CAAC;AAEtD;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IAC7B;;OAEG;IACH;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAED,QAAQ;QACN,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\"AzureCliCredential is not supported in the browser.\");\nconst logger = credentialLogger(\"AzureCliCredential\");\n\n/**\n * This credential will use the currently logged-in user login information\n * via the Azure CLI ('az') commandline tool.\n */\nexport class AzureCliCredential implements TokenCredential {\n /**\n * Only available in Node.js\n */\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}

View File

@@ -0,0 +1,175 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { checkTenantId, processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
import { credentialLogger, formatError, formatSuccess } from "../util/logging";
import { ensureValidScopeForDevTimeCreds, getScopeResource } from "../util/scopeUtils";
import { CredentialUnavailableError } from "../errors";
import child_process from "child_process";
import { tracingClient } from "../util/tracing";
/**
* Mockable reference to the CLI credential cliCredentialFunctions
* @internal
*/
export const cliCredentialInternals = {
/**
* @internal
*/
getSafeWorkingDir() {
if (process.platform === "win32") {
if (!process.env.SystemRoot) {
throw new Error("Azure CLI credential expects a 'SystemRoot' environment variable");
}
return process.env.SystemRoot;
}
else {
return "/bin";
}
},
/**
* Gets the access token from Azure CLI
* @param resource - The resource to use when getting the token
* @internal
*/
async getAzureCliAccessToken(resource, tenantId, timeout) {
let tenantSection = [];
if (tenantId) {
tenantSection = ["--tenant", tenantId];
}
return new Promise((resolve, reject) => {
try {
child_process.execFile("az", [
"account",
"get-access-token",
"--output",
"json",
"--resource",
resource,
...tenantSection,
], { cwd: cliCredentialInternals.getSafeWorkingDir(), shell: true, timeout }, (error, stdout, stderr) => {
resolve({ stdout: stdout, stderr: stderr, error });
});
}
catch (err) {
reject(err);
}
});
},
};
const logger = credentialLogger("AzureCliCredential");
/**
* This credential will use the currently logged-in user login information
* via the Azure CLI ('az') commandline tool.
* To do so, it will read the user access token and expire time
* with Azure CLI command "az account get-access-token".
*/
export class AzureCliCredential {
/**
* Creates an instance of the {@link AzureCliCredential}.
*
* To use this credential, ensure that you have already logged
* in via the 'az' tool using the command "az login" from the commandline.
*
* @param options - Options, to optionally allow multi-tenant requests.
*/
constructor(options) {
if (options === null || options === void 0 ? void 0 : options.tenantId) {
checkTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId);
this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId;
}
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
this.timeout = options === null || options === void 0 ? void 0 : options.processTimeoutInMs;
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(scopes, options = {}) {
const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds);
if (tenantId) {
checkTenantId(logger, tenantId);
}
const scope = typeof scopes === "string" ? scopes : scopes[0];
logger.getToken.info(`Using the scope ${scope}`);
return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {
var _a, _b, _c, _d;
try {
ensureValidScopeForDevTimeCreds(scope, logger);
const resource = getScopeResource(scope);
const obj = await cliCredentialInternals.getAzureCliAccessToken(resource, tenantId, this.timeout);
const specificScope = (_a = obj.stderr) === null || _a === void 0 ? void 0 : _a.match("(.*)az login --scope(.*)");
const isLoginError = ((_b = obj.stderr) === null || _b === void 0 ? void 0 : _b.match("(.*)az login(.*)")) && !specificScope;
const isNotInstallError = ((_c = obj.stderr) === null || _c === void 0 ? void 0 : _c.match("az:(.*)not found")) || ((_d = obj.stderr) === null || _d === void 0 ? void 0 : _d.startsWith("'az' is not recognized"));
if (isNotInstallError) {
const error = new CredentialUnavailableError("Azure CLI could not be found. Please visit https://aka.ms/azure-cli for installation instructions and then, once installed, authenticate to your Azure account using 'az login'.");
logger.getToken.info(formatError(scopes, error));
throw error;
}
if (isLoginError) {
const error = new CredentialUnavailableError("Please run 'az login' from a command prompt to authenticate before using this credential.");
logger.getToken.info(formatError(scopes, error));
throw error;
}
try {
const responseData = obj.stdout;
const response = this.parseRawResponse(responseData);
logger.getToken.info(formatSuccess(scopes));
return response;
}
catch (e) {
if (obj.stderr) {
throw new CredentialUnavailableError(obj.stderr);
}
throw e;
}
}
catch (err) {
const error = err.name === "CredentialUnavailableError"
? err
: new CredentialUnavailableError(err.message || "Unknown error while trying to retrieve the access token");
logger.getToken.info(formatError(scopes, error));
throw error;
}
});
}
/**
* Parses the raw JSON response from the Azure CLI into a usable AccessToken object
*
* @param rawResponse - The raw JSON response from the Azure CLI
* @returns An access token with the expiry time parsed from the raw response
*
* The expiryTime of the credential's access token, in milliseconds, is calculated as follows:
*
* When available, expires_on (introduced in Azure CLI v2.54.0) will be preferred. Otherwise falls back to expiresOn.
*/
parseRawResponse(rawResponse) {
const response = JSON.parse(rawResponse);
const token = response.accessToken;
// if available, expires_on will be a number representing seconds since epoch.
// ensure it's a number or NaN
let expiresOnTimestamp = Number.parseInt(response.expires_on, 10) * 1000;
if (!isNaN(expiresOnTimestamp)) {
logger.getToken.info("expires_on is available and is valid, using it");
return {
token,
expiresOnTimestamp,
tokenType: "Bearer",
};
}
// fallback to the older expiresOn - an RFC3339 date string
expiresOnTimestamp = new Date(response.expiresOn).getTime();
// ensure expiresOn is well-formatted
if (isNaN(expiresOnTimestamp)) {
throw new CredentialUnavailableError(`Unexpected response from Azure CLI when getting token. Expected "expiresOn" to be a RFC3339 date string. Got: "${response.expiresOn}"`);
}
return {
token,
expiresOnTimestamp,
tokenType: "Bearer",
};
}
}
//# sourceMappingURL=azureCliCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=azureCliCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"azureCliCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/azureCliCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Options for the {@link AzureCliCredential}\n */\nexport interface AzureCliCredentialOptions extends MultiTenantTokenCredentialOptions {\n /**\n * Allows specifying a tenant ID\n */\n tenantId?: string;\n /**\n * Process timeout configurable for making token requests, provided in milliseconds\n */\n processTimeoutInMs?: number;\n}\n"]}

View File

@@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
const BrowserNotSupportedError = new Error("AzureDeveloperCliCredential is not supported in the browser.");
const logger = credentialLogger("AzureDeveloperCliCredential");
/**
* This credential will use the currently logged-in user login information
* via the Azure Developer CLI ('azd') commandline tool.
*/
export class AzureDeveloperCliCredential {
/**
* Only available in Node.js
*/
constructor() {
logger.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
getToken() {
logger.getToken.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
}
//# sourceMappingURL=azureDeveloperCliCredential.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"azureDeveloperCliCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/azureDeveloperCliCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,8DAA8D,CAC/D,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,6BAA6B,CAAC,CAAC;AAE/D;;;GAGG;AACH,MAAM,OAAO,2BAA2B;IACtC;;OAEG;IACH;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAED,QAAQ;QACN,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"AzureDeveloperCliCredential is not supported in the browser.\",\n);\nconst logger = credentialLogger(\"AzureDeveloperCliCredential\");\n\n/**\n * This credential will use the currently logged-in user login information\n * via the Azure Developer CLI ('azd') commandline tool.\n */\nexport class AzureDeveloperCliCredential implements TokenCredential {\n /**\n * Only available in Node.js\n */\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}

View File

@@ -0,0 +1,171 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError, formatSuccess } from "../util/logging";
import { CredentialUnavailableError } from "../errors";
import child_process from "child_process";
import { checkTenantId, processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
import { tracingClient } from "../util/tracing";
import { ensureValidScopeForDevTimeCreds } from "../util/scopeUtils";
/**
* Mockable reference to the Developer CLI credential cliCredentialFunctions
* @internal
*/
export const developerCliCredentialInternals = {
/**
* @internal
*/
getSafeWorkingDir() {
if (process.platform === "win32") {
if (!process.env.SystemRoot) {
throw new Error("Azure Developer CLI credential expects a 'SystemRoot' environment variable");
}
return process.env.SystemRoot;
}
else {
return "/bin";
}
},
/**
* Gets the access token from Azure Developer CLI
* @param scopes - The scopes to use when getting the token
* @internal
*/
async getAzdAccessToken(scopes, tenantId, timeout) {
let tenantSection = [];
if (tenantId) {
tenantSection = ["--tenant-id", tenantId];
}
return new Promise((resolve, reject) => {
try {
child_process.execFile("azd", [
"auth",
"token",
"--output",
"json",
...scopes.reduce((previous, current) => previous.concat("--scope", current), []),
...tenantSection,
], {
cwd: developerCliCredentialInternals.getSafeWorkingDir(),
timeout,
}, (error, stdout, stderr) => {
resolve({ stdout, stderr, error });
});
}
catch (err) {
reject(err);
}
});
},
};
const logger = credentialLogger("AzureDeveloperCliCredential");
/**
* Azure Developer CLI is a command-line interface tool that allows developers to create, manage, and deploy
* resources in Azure. It's built on top of the Azure CLI and provides additional functionality specific
* to Azure developers. It allows users to authenticate as a user and/or a service principal against
* <a href="https://learn.microsoft.com/entra/fundamentals/">Microsoft Entra ID</a>. The
* AzureDeveloperCliCredential authenticates in a development environment and acquires a token on behalf of
* the logged-in user or service principal in the Azure Developer CLI. It acts as the Azure Developer CLI logged in user or
* service principal and executes an Azure CLI command underneath to authenticate the application against
* Microsoft Entra ID.
*
* <h2> Configure AzureDeveloperCliCredential </h2>
*
* To use this credential, the developer needs to authenticate locally in Azure Developer CLI using one of the
* commands below:
*
* <ol>
* <li>Run "azd auth login" in Azure Developer CLI to authenticate interactively as a user.</li>
* <li>Run "azd auth login --client-id clientID --client-secret clientSecret
* --tenant-id tenantID" to authenticate as a service principal.</li>
* </ol>
*
* You may need to repeat this process after a certain time period, depending on the refresh token validity in your
* organization. Generally, the refresh token validity period is a few weeks to a few months.
* AzureDeveloperCliCredential will prompt you to sign in again.
*/
export class AzureDeveloperCliCredential {
/**
* Creates an instance of the {@link AzureDeveloperCliCredential}.
*
* To use this credential, ensure that you have already logged
* in via the 'azd' tool using the command "azd auth login" from the commandline.
*
* @param options - Options, to optionally allow multi-tenant requests.
*/
constructor(options) {
if (options === null || options === void 0 ? void 0 : options.tenantId) {
checkTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId);
this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId;
}
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
this.timeout = options === null || options === void 0 ? void 0 : options.processTimeoutInMs;
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(scopes, options = {}) {
const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds);
if (tenantId) {
checkTenantId(logger, tenantId);
}
let scopeList;
if (typeof scopes === "string") {
scopeList = [scopes];
}
else {
scopeList = scopes;
}
logger.getToken.info(`Using the scopes ${scopes}`);
return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {
var _a, _b, _c, _d;
try {
scopeList.forEach((scope) => {
ensureValidScopeForDevTimeCreds(scope, logger);
});
const obj = await developerCliCredentialInternals.getAzdAccessToken(scopeList, tenantId, this.timeout);
const isNotLoggedInError = ((_a = obj.stderr) === null || _a === void 0 ? void 0 : _a.match("not logged in, run `azd login` to login")) ||
((_b = obj.stderr) === null || _b === void 0 ? void 0 : _b.match("not logged in, run `azd auth login` to login"));
const isNotInstallError = ((_c = obj.stderr) === null || _c === void 0 ? void 0 : _c.match("azd:(.*)not found")) ||
((_d = obj.stderr) === null || _d === void 0 ? void 0 : _d.startsWith("'azd' is not recognized"));
if (isNotInstallError || (obj.error && obj.error.code === "ENOENT")) {
const error = new CredentialUnavailableError("Azure Developer CLI couldn't be found. To mitigate this issue, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.");
logger.getToken.info(formatError(scopes, error));
throw error;
}
if (isNotLoggedInError) {
const error = new CredentialUnavailableError("Please run 'azd auth login' from a command prompt to authenticate before using this credential. For more information, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.");
logger.getToken.info(formatError(scopes, error));
throw error;
}
try {
const resp = JSON.parse(obj.stdout);
logger.getToken.info(formatSuccess(scopes));
return {
token: resp.token,
expiresOnTimestamp: new Date(resp.expiresOn).getTime(),
tokenType: "Bearer",
};
}
catch (e) {
if (obj.stderr) {
throw new CredentialUnavailableError(obj.stderr);
}
throw e;
}
}
catch (err) {
const error = err.name === "CredentialUnavailableError"
? err
: new CredentialUnavailableError(err.message || "Unknown error while trying to retrieve the access token");
logger.getToken.info(formatError(scopes, error));
throw error;
}
});
}
}
//# sourceMappingURL=azureDeveloperCliCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=azureDeveloperCliCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"azureDeveloperCliCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/azureDeveloperCliCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Options for the {@link AzureDeveloperCliCredential}\n */\nexport interface AzureDeveloperCliCredentialOptions extends MultiTenantTokenCredentialOptions {\n /**\n * Allows specifying a tenant ID\n */\n tenantId?: string;\n /**\n * Process timeout configurable for making token requests, provided in milliseconds\n */\n processTimeoutInMs?: number;\n}\n"]}

View File

@@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
const BrowserNotSupportedError = new Error("AzurePipelinesCredential is not supported in the browser.");
const logger = credentialLogger("AzurePipelinesCredential");
/**
* Enables authentication to Microsoft Entra ID using a PEM-encoded
* certificate that is assigned to an App Registration.
*/
export class AzurePipelinesCredential {
/**
* Only available in Node.js
*/
constructor() {
logger.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
getToken() {
logger.getToken.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
}
//# sourceMappingURL=azurePipelinesCredential.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"azurePipelinesCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/azurePipelinesCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,2DAA2D,CAC5D,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,0BAA0B,CAAC,CAAC;AAE5D;;;GAGG;AACH,MAAM,OAAO,wBAAwB;IACnC;;OAEG;IACH;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,QAAQ;QACb,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"AzurePipelinesCredential is not supported in the browser.\",\n);\nconst logger = credentialLogger(\"AzurePipelinesCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID using a PEM-encoded\n * certificate that is assigned to an App Registration.\n */\nexport class AzurePipelinesCredential implements TokenCredential {\n /**\n * Only available in Node.js\n */\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}

View File

@@ -0,0 +1,141 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { AuthenticationError, CredentialUnavailableError } from "../errors";
import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline";
import { ClientAssertionCredential } from "./clientAssertionCredential";
import { IdentityClient } from "../client/identityClient";
import { checkTenantId } from "../util/tenantIdUtils";
import { credentialLogger } from "../util/logging";
const credentialName = "AzurePipelinesCredential";
const logger = credentialLogger(credentialName);
const OIDC_API_VERSION = "7.1";
/**
* This credential is designed to be used in Azure Pipelines with service connections
* as a setup for workload identity federation.
*/
export class AzurePipelinesCredential {
/**
* AzurePipelinesCredential supports Federated Identity on Azure Pipelines through Service Connections.
* @param tenantId - tenantId associated with the service connection
* @param clientId - clientId associated with the service connection
* @param serviceConnectionId - Unique ID for the service connection, as found in the querystring's resourceId key
* @param systemAccessToken - The pipeline's <see href="https://learn.microsoft.com/azure/devops/pipelines/build/variables?view=azure-devops%26tabs=yaml#systemaccesstoken">System.AccessToken</see> value.
* @param options - The identity client options to use for authentication.
*/
constructor(tenantId, clientId, serviceConnectionId, systemAccessToken, options = {}) {
var _a, _b;
if (!clientId) {
throw new CredentialUnavailableError(`${credentialName}: is unavailable. clientId is a required parameter.`);
}
if (!tenantId) {
throw new CredentialUnavailableError(`${credentialName}: is unavailable. tenantId is a required parameter.`);
}
if (!serviceConnectionId) {
throw new CredentialUnavailableError(`${credentialName}: is unavailable. serviceConnectionId is a required parameter.`);
}
if (!systemAccessToken) {
throw new CredentialUnavailableError(`${credentialName}: is unavailable. systemAccessToken is a required parameter.`);
}
// Allow these headers to be logged for troubleshooting by AzurePipelines.
options.loggingOptions = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.loggingOptions), { additionalAllowedHeaderNames: [
...((_b = (_a = options.loggingOptions) === null || _a === void 0 ? void 0 : _a.additionalAllowedHeaderNames) !== null && _b !== void 0 ? _b : []),
"x-vss-e2eid",
"x-msedge-ref",
] });
this.identityClient = new IdentityClient(options);
checkTenantId(logger, tenantId);
logger.info(`Invoking AzurePipelinesCredential with tenant ID: ${tenantId}, client ID: ${clientId}, and service connection ID: ${serviceConnectionId}`);
if (!process.env.SYSTEM_OIDCREQUESTURI) {
throw new CredentialUnavailableError(`${credentialName}: is unavailable. Ensure that you're running this task in an Azure Pipeline, so that following missing system variable(s) can be defined- "SYSTEM_OIDCREQUESTURI"`);
}
const oidcRequestUrl = `${process.env.SYSTEM_OIDCREQUESTURI}?api-version=${OIDC_API_VERSION}&serviceConnectionId=${serviceConnectionId}`;
logger.info(`Invoking ClientAssertionCredential with tenant ID: ${tenantId}, client ID: ${clientId} and service connection ID: ${serviceConnectionId}`);
this.clientAssertionCredential = new ClientAssertionCredential(tenantId, clientId, this.requestOidcToken.bind(this, oidcRequestUrl, systemAccessToken), options);
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} or {@link AuthenticationError} will be thrown with the details of the failure.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(scopes, options) {
if (!this.clientAssertionCredential) {
const errorMessage = `${credentialName}: is unavailable. To use Federation Identity in Azure Pipelines, the following parameters are required -
tenantId,
clientId,
serviceConnectionId,
systemAccessToken,
"SYSTEM_OIDCREQUESTURI".
See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;
logger.error(errorMessage);
throw new CredentialUnavailableError(errorMessage);
}
logger.info("Invoking getToken() of Client Assertion Credential");
return this.clientAssertionCredential.getToken(scopes, options);
}
/**
*
* @param oidcRequestUrl - oidc request url
* @param systemAccessToken - system access token
* @returns OIDC token from Azure Pipelines
*/
async requestOidcToken(oidcRequestUrl, systemAccessToken) {
logger.info("Requesting OIDC token from Azure Pipelines...");
logger.info(oidcRequestUrl);
const request = createPipelineRequest({
url: oidcRequestUrl,
method: "POST",
headers: createHttpHeaders({
"Content-Type": "application/json",
Authorization: `Bearer ${systemAccessToken}`,
// Prevents the service from responding with a redirect HTTP status code (useful for automation).
"X-TFS-FedAuthRedirect": "Suppress",
}),
});
const response = await this.identityClient.sendRequest(request);
return handleOidcResponse(response);
}
}
export function handleOidcResponse(response) {
// OIDC token is present in `bodyAsText` field
const text = response.bodyAsText;
if (!text) {
logger.error(`${credentialName}: Authentication Failed. Received null token from OIDC request. Response status- ${response.status}. Complete response - ${JSON.stringify(response)}`);
throw new AuthenticationError(response.status, {
error: `${credentialName}: Authentication Failed. Received null token from OIDC request.`,
error_description: `${JSON.stringify(response)}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`,
});
}
try {
const result = JSON.parse(text);
if (result === null || result === void 0 ? void 0 : result.oidcToken) {
return result.oidcToken;
}
else {
const errorMessage = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`;
let errorDescription = ``;
if (response.status !== 200) {
errorDescription = `Response body = ${text}. Response Headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")} and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;
}
logger.error(errorMessage);
logger.error(errorDescription);
throw new AuthenticationError(response.status, {
error: errorMessage,
error_description: errorDescription,
});
}
}
catch (e) {
const errorDetails = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`;
logger.error(`Response from service = ${text}, Response Headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")}
and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}, error message = ${e.message}`);
logger.error(errorDetails);
throw new AuthenticationError(response.status, {
error: errorDetails,
error_description: `Response = ${text}. Response headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")} and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`,
});
}
}
//# sourceMappingURL=azurePipelinesCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=azurePipelinesCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"azurePipelinesCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/azurePipelinesCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AuthorityValidationOptions } from \"./authorityValidationOptions\";\nimport { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Optional parameters for the {@link AzurePipelinesCredential} class.\n */\nexport interface AzurePipelinesCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n CredentialPersistenceOptions,\n AuthorityValidationOptions {}\n"]}

View File

@@ -0,0 +1,22 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
const BrowserNotSupportedError = new Error("AzurePowerShellCredential is not supported in the browser.");
const logger = credentialLogger("AzurePowerShellCredential");
/**
* This credential will use the currently-logged-in user's login information via the Azure Power Shell command line tool.
*/
export class AzurePowerShellCredential {
/**
* Only available in Node.js
*/
constructor() {
logger.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
getToken() {
logger.getToken.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
}
//# sourceMappingURL=azurePowerShellCredential.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"azurePowerShellCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/azurePowerShellCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,4DAA4D,CAC7D,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAE7D;;GAEG;AACH,MAAM,OAAO,yBAAyB;IACpC;;OAEG;IACH;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAED,QAAQ;QACN,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"AzurePowerShellCredential is not supported in the browser.\",\n);\nconst logger = credentialLogger(\"AzurePowerShellCredential\");\n\n/**\n * This credential will use the currently-logged-in user's login information via the Azure Power Shell command line tool.\n */\nexport class AzurePowerShellCredential implements TokenCredential {\n /**\n * Only available in Node.js\n */\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}

View File

@@ -0,0 +1,229 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { checkTenantId, processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
import { credentialLogger, formatError, formatSuccess } from "../util/logging";
import { ensureValidScopeForDevTimeCreds, getScopeResource } from "../util/scopeUtils";
import { CredentialUnavailableError } from "../errors";
import { processUtils } from "../util/processUtils";
import { tracingClient } from "../util/tracing";
const logger = credentialLogger("AzurePowerShellCredential");
const isWindows = process.platform === "win32";
/**
* Returns a platform-appropriate command name by appending ".exe" on Windows.
*
* @internal
*/
export function formatCommand(commandName) {
if (isWindows) {
return `${commandName}.exe`;
}
else {
return commandName;
}
}
/**
* Receives a list of commands to run, executes them, then returns the outputs.
* If anything fails, an error is thrown.
* @internal
*/
async function runCommands(commands, timeout) {
const results = [];
for (const command of commands) {
const [file, ...parameters] = command;
const result = (await processUtils.execFile(file, parameters, {
encoding: "utf8",
timeout,
}));
results.push(result);
}
return results;
}
/**
* Known PowerShell errors
* @internal
*/
export const powerShellErrors = {
login: "Run Connect-AzAccount to login",
installed: "The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory",
};
/**
* Messages to use when throwing in this credential.
* @internal
*/
export const powerShellPublicErrorMessages = {
login: "Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.",
installed: `The 'Az.Account' module >= 2.2.0 is not installed. Install the Azure Az PowerShell module with: "Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force".`,
troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`,
};
// PowerShell Azure User not logged in error check.
const isLoginError = (err) => err.message.match(`(.*)${powerShellErrors.login}(.*)`);
// Az Module not Installed in Azure PowerShell check.
const isNotInstalledError = (err) => err.message.match(powerShellErrors.installed);
/**
* The PowerShell commands to be tried, in order.
*
* @internal
*/
export const commandStack = [formatCommand("pwsh")];
if (isWindows) {
commandStack.push(formatCommand("powershell"));
}
/**
* This credential will use the currently logged-in user information from the
* Azure PowerShell module. To do so, it will read the user access token and
* expire time with Azure PowerShell command `Get-AzAccessToken -ResourceUrl {ResourceScope}`
*/
export class AzurePowerShellCredential {
/**
* Creates an instance of the {@link AzurePowerShellCredential}.
*
* To use this credential:
* - Install the Azure Az PowerShell module with:
* `Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force`.
* - You have already logged in to Azure PowerShell using the command
* `Connect-AzAccount` from the command line.
*
* @param options - Options, to optionally allow multi-tenant requests.
*/
constructor(options) {
if (options === null || options === void 0 ? void 0 : options.tenantId) {
checkTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId);
this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId;
}
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
this.timeout = options === null || options === void 0 ? void 0 : options.processTimeoutInMs;
}
/**
* Gets the access token from Azure PowerShell
* @param resource - The resource to use when getting the token
*/
async getAzurePowerShellAccessToken(resource, tenantId, timeout) {
// Clone the stack to avoid mutating it while iterating
for (const powerShellCommand of [...commandStack]) {
try {
await runCommands([[powerShellCommand, "/?"]], timeout);
}
catch (e) {
// Remove this credential from the original stack so that we don't try it again.
commandStack.shift();
continue;
}
const results = await runCommands([
[
powerShellCommand,
"-NoProfile",
"-NonInteractive",
"-Command",
`
$tenantId = "${tenantId !== null && tenantId !== void 0 ? tenantId : ""}"
$m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru
$useSecureString = $m.Version -ge [version]'2.17.0'
$params = @{
ResourceUrl = "${resource}"
}
if ($tenantId.Length -gt 0) {
$params["TenantId"] = $tenantId
}
if ($useSecureString) {
$params["AsSecureString"] = $true
}
$token = Get-AzAccessToken @params
$result = New-Object -TypeName PSObject
$result | Add-Member -MemberType NoteProperty -Name ExpiresOn -Value $token.ExpiresOn
if ($useSecureString) {
$result | Add-Member -MemberType NoteProperty -Name Token -Value (ConvertFrom-SecureString -AsPlainText $token.Token)
} else {
$result | Add-Member -MemberType NoteProperty -Name Token -Value $token.Token
}
Write-Output (ConvertTo-Json $result)
`,
],
]);
const result = results[0];
return parseJsonToken(result);
}
throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`);
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If the authentication cannot be performed through PowerShell, a {@link CredentialUnavailableError} will be thrown.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this TokenCredential implementation might make.
*/
async getToken(scopes, options = {}) {
return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {
const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds);
const scope = typeof scopes === "string" ? scopes : scopes[0];
if (tenantId) {
checkTenantId(logger, tenantId);
}
try {
ensureValidScopeForDevTimeCreds(scope, logger);
logger.getToken.info(`Using the scope ${scope}`);
const resource = getScopeResource(scope);
const response = await this.getAzurePowerShellAccessToken(resource, tenantId, this.timeout);
logger.getToken.info(formatSuccess(scopes));
return {
token: response.Token,
expiresOnTimestamp: new Date(response.ExpiresOn).getTime(),
tokenType: "Bearer",
};
}
catch (err) {
if (isNotInstalledError(err)) {
const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed);
logger.getToken.info(formatError(scope, error));
throw error;
}
else if (isLoginError(err)) {
const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login);
logger.getToken.info(formatError(scope, error));
throw error;
}
const error = new CredentialUnavailableError(`${err}. ${powerShellPublicErrorMessages.troubleshoot}`);
logger.getToken.info(formatError(scope, error));
throw error;
}
});
}
}
/**
*
* @internal
*/
export async function parseJsonToken(result) {
const jsonRegex = /{[^{}]*}/g;
const matches = result.match(jsonRegex);
let resultWithoutToken = result;
if (matches) {
try {
for (const item of matches) {
try {
const jsonContent = JSON.parse(item);
if (jsonContent === null || jsonContent === void 0 ? void 0 : jsonContent.Token) {
resultWithoutToken = resultWithoutToken.replace(item, "");
if (resultWithoutToken) {
logger.getToken.warning(resultWithoutToken);
}
return jsonContent;
}
}
catch (e) {
continue;
}
}
}
catch (e) {
throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`);
}
}
throw new Error(`No access token found in the output. Received output: ${result}`);
}
//# sourceMappingURL=azurePowerShellCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=azurePowerShellCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"azurePowerShellCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/azurePowerShellCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Options for the {@link AzurePowerShellCredential}\n */\nexport interface AzurePowerShellCredentialOptions extends MultiTenantTokenCredentialOptions {\n /**\n * Allows specifying a tenant ID\n */\n tenantId?: string;\n /**\n * Process timeout configurable for making token requests, provided in milliseconds\n */\n processTimeoutInMs?: number;\n}\n"]}

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=brokerAuthOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"brokerAuthOptions.js","sourceRoot":"","sources":["../../../src/credentials/brokerAuthOptions.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport { BrokerOptions } from \"../msal/nodeFlows/brokerOptions\";\n\n/**\n * Configuration options for InteractiveBrowserCredential\n * to support WAM Broker Authentication.\n */\n\nexport interface BrokerAuthOptions {\n /**\n * Options to allow broker authentication when using InteractiveBrowserCredential\n *\n */\n brokerOptions?: BrokerOptions;\n}\n"]}

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=browserCustomizationOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"browserCustomizationOptions.js","sourceRoot":"","sources":["../../../src/credentials/browserCustomizationOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Shared configuration options for browser customization\n */\nexport interface BrowserCustomizationOptions {\n /**\n * Shared configuration options for browser customization\n */\n browserCustomizationOptions?: {\n /**\n * Format for error messages for display in browser\n */\n errorMessage?: string;\n /**\n * Format for success messages for display in browser\n */\n successMessage?: string;\n };\n}\n"]}

View File

@@ -0,0 +1,89 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { AggregateAuthenticationError, CredentialUnavailableError } from "../errors";
import { credentialLogger, formatError, formatSuccess } from "../util/logging";
import { tracingClient } from "../util/tracing";
/**
* @internal
*/
export const logger = credentialLogger("ChainedTokenCredential");
/**
* Enables multiple `TokenCredential` implementations to be tried in order
* until one of the getToken methods returns an access token.
*/
export class ChainedTokenCredential {
/**
* Creates an instance of ChainedTokenCredential using the given credentials.
*
* @param sources - `TokenCredential` implementations to be tried in order.
*
* Example usage:
* ```ts snippet:chained_token_credential_example
* import { ClientSecretCredential, ChainedTokenCredential } from "@azure/identity";
*
* const tenantId = "<tenant-id>";
* const clientId = "<client-id>";
* const clientSecret = "<client-secret>";
* const anotherClientId = "<another-client-id>";
* const anotherSecret = "<another-client-secret>";
* const firstCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
* const secondCredential = new ClientSecretCredential(tenantId, anotherClientId, anotherSecret);
* const credentialChain = new ChainedTokenCredential(firstCredential, secondCredential);
* ```
*/
constructor(...sources) {
this._sources = [];
this._sources = sources;
}
/**
* Returns the first access token returned by one of the chained
* `TokenCredential` implementations. Throws an {@link AggregateAuthenticationError}
* when one or more credentials throws an {@link AuthenticationError} and
* no credentials have returned an access token.
*
* This method is called automatically by Azure SDK client libraries. You may call this method
* directly, but you must also handle token caching and token refreshing.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* `TokenCredential` implementation might make.
*/
async getToken(scopes, options = {}) {
const { token } = await this.getTokenInternal(scopes, options);
return token;
}
async getTokenInternal(scopes, options = {}) {
let token = null;
let successfulCredential;
const errors = [];
return tracingClient.withSpan("ChainedTokenCredential.getToken", options, async (updatedOptions) => {
for (let i = 0; i < this._sources.length && token === null; i++) {
try {
token = await this._sources[i].getToken(scopes, updatedOptions);
successfulCredential = this._sources[i];
}
catch (err) {
if (err.name === "CredentialUnavailableError" ||
err.name === "AuthenticationRequiredError") {
errors.push(err);
}
else {
logger.getToken.info(formatError(scopes, err));
throw err;
}
}
}
if (!token && errors.length > 0) {
const err = new AggregateAuthenticationError(errors, "ChainedTokenCredential authentication failed.");
logger.getToken.info(formatError(scopes, err));
throw err;
}
logger.getToken.info(`Result for ${successfulCredential.constructor.name}: ${formatSuccess(scopes)}`);
if (token === null) {
throw new CredentialUnavailableError("Failed to retrieve a valid token");
}
return { token, successfulCredential };
});
}
}
//# sourceMappingURL=chainedTokenCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,22 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
const BrowserNotSupportedError = new Error("ClientAssertionCredential is not supported in the browser.");
const logger = credentialLogger("ClientAssertionCredential");
/**
* Authenticates a service principal with a JWT assertion.
*/
export class ClientAssertionCredential {
/**
* Only available in Node.js
*/
constructor() {
logger.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
getToken() {
logger.getToken.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
}
//# sourceMappingURL=clientAssertionCredential.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"clientAssertionCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/clientAssertionCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,4DAA4D,CAC7D,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAE7D;;GAEG;AACH,MAAM,OAAO,yBAAyB;IACpC;;OAEG;IACH;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,QAAQ;QACb,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"ClientAssertionCredential is not supported in the browser.\",\n);\nconst logger = credentialLogger(\"ClientAssertionCredential\");\n\n/**\n * Authenticates a service principal with a JWT assertion.\n */\nexport class ClientAssertionCredential implements TokenCredential {\n /**\n * Only available in Node.js\n */\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}

View File

@@ -0,0 +1,55 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createMsalClient } from "../msal/nodeFlows/msalClient";
import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
import { CredentialUnavailableError } from "../errors";
import { credentialLogger } from "../util/logging";
import { tracingClient } from "../util/tracing";
const logger = credentialLogger("ClientAssertionCredential");
/**
* Authenticates a service principal with a JWT assertion.
*/
export class ClientAssertionCredential {
/**
* Creates an instance of the ClientAssertionCredential with the details
* needed to authenticate against Microsoft Entra ID with a client
* assertion provided by the developer through the `getAssertion` function parameter.
*
* @param tenantId - The Microsoft Entra tenant (directory) ID.
* @param clientId - The client (application) ID of an App Registration in the tenant.
* @param getAssertion - A function that retrieves the assertion for the credential to use.
* @param options - Options for configuring the client which makes the authentication request.
*/
constructor(tenantId, clientId, getAssertion, options = {}) {
if (!tenantId) {
throw new CredentialUnavailableError("ClientAssertionCredential: tenantId is a required parameter.");
}
if (!clientId) {
throw new CredentialUnavailableError("ClientAssertionCredential: clientId is a required parameter.");
}
if (!getAssertion) {
throw new CredentialUnavailableError("ClientAssertionCredential: clientAssertion is a required parameter.");
}
this.tenantId = tenantId;
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
this.options = options;
this.getAssertion = getAssertion;
this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: this.options }));
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(scopes, options = {}) {
return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger);
const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
return this.msalClient.getTokenByClientAssertion(arrayScopes, this.getAssertion, newOptions);
});
}
}
//# sourceMappingURL=clientAssertionCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=clientAssertionCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"clientAssertionCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/clientAssertionCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AuthorityValidationOptions } from \"./authorityValidationOptions\";\nimport { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Options for the {@link ClientAssertionCredential}\n */\nexport interface ClientAssertionCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n CredentialPersistenceOptions,\n AuthorityValidationOptions {}\n"]}

View File

@@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
const BrowserNotSupportedError = new Error("ClientCertificateCredential is not supported in the browser.");
const logger = credentialLogger("ClientCertificateCredential");
/**
* Enables authentication to Microsoft Entra ID using a PEM-encoded
* certificate that is assigned to an App Registration.
*/
export class ClientCertificateCredential {
/**
* Only available in Node.js
*/
constructor() {
logger.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
getToken() {
logger.getToken.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
}
//# sourceMappingURL=clientCertificateCredential.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"clientCertificateCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/clientCertificateCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,8DAA8D,CAC/D,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,6BAA6B,CAAC,CAAC;AAE/D;;;GAGG;AACH,MAAM,OAAO,2BAA2B;IACtC;;OAEG;IACH;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,QAAQ;QACb,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"ClientCertificateCredential is not supported in the browser.\",\n);\nconst logger = credentialLogger(\"ClientCertificateCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID using a PEM-encoded\n * certificate that is assigned to an App Registration.\n */\nexport class ClientCertificateCredential implements TokenCredential {\n /**\n * Only available in Node.js\n */\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}

View File

@@ -0,0 +1,119 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createMsalClient } from "../msal/nodeFlows/msalClient";
import { createHash, createPrivateKey } from "crypto";
import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
import { credentialLogger } from "../util/logging";
import { readFile } from "fs/promises";
import { tracingClient } from "../util/tracing";
const credentialName = "ClientCertificateCredential";
const logger = credentialLogger(credentialName);
/**
* Enables authentication to Microsoft Entra ID using a PEM-encoded
* certificate that is assigned to an App Registration. More information
* on how to configure certificate authentication can be found here:
*
* https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad
*
*/
export class ClientCertificateCredential {
constructor(tenantId, clientId, certificatePathOrConfiguration, options = {}) {
if (!tenantId || !clientId) {
throw new Error(`${credentialName}: tenantId and clientId are required parameters.`);
}
this.tenantId = tenantId;
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
this.sendCertificateChain = options.sendCertificateChain;
this.certificateConfiguration = Object.assign({}, (typeof certificatePathOrConfiguration === "string"
? {
certificatePath: certificatePathOrConfiguration,
}
: certificatePathOrConfiguration));
const certificate = this.certificateConfiguration.certificate;
const certificatePath = this.certificateConfiguration.certificatePath;
if (!this.certificateConfiguration || !(certificate || certificatePath)) {
throw new Error(`${credentialName}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
}
if (certificate && certificatePath) {
throw new Error(`${credentialName}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
}
this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options }));
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(scopes, options = {}) {
return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {
newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger);
const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
const certificate = await this.buildClientCertificate();
return this.msalClient.getTokenByClientCertificate(arrayScopes, certificate, newOptions);
});
}
async buildClientCertificate() {
var _a;
const parts = await parseCertificate(this.certificateConfiguration, (_a = this.sendCertificateChain) !== null && _a !== void 0 ? _a : false);
let privateKey;
if (this.certificateConfiguration.certificatePassword !== undefined) {
privateKey = createPrivateKey({
key: parts.certificateContents,
passphrase: this.certificateConfiguration.certificatePassword,
format: "pem",
})
.export({
format: "pem",
type: "pkcs8",
})
.toString();
}
else {
privateKey = parts.certificateContents;
}
return {
thumbprint: parts.thumbprint,
privateKey,
x5c: parts.x5c,
};
}
}
/**
* Parses a certificate into its relevant parts
*
* @param certificateConfiguration - The certificate contents or path to the certificate
* @param sendCertificateChain - true if the entire certificate chain should be sent for SNI, false otherwise
* @returns The parsed certificate parts and the certificate contents
*/
export async function parseCertificate(certificateConfiguration, sendCertificateChain) {
const certificate = certificateConfiguration.certificate;
const certificatePath = certificateConfiguration.certificatePath;
const certificateContents = certificate || (await readFile(certificatePath, "utf8"));
const x5c = sendCertificateChain ? certificateContents : undefined;
const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/g;
const publicKeys = [];
// Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c
let match;
do {
match = certificatePattern.exec(certificateContents);
if (match) {
publicKeys.push(match[3]);
}
} while (match);
if (publicKeys.length === 0) {
throw new Error("The file at the specified path does not contain a PEM-encoded certificate.");
}
const thumbprint = createHash("sha1")
.update(Buffer.from(publicKeys[0], "base64"))
.digest("hex")
.toUpperCase();
return {
certificateContents,
thumbprint,
x5c,
};
}
//# sourceMappingURL=clientCertificateCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=clientCertificateCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"clientCertificateCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/clientCertificateCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AuthorityValidationOptions } from \"./authorityValidationOptions\";\nimport { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Optional parameters for the {@link ClientCertificateCredential} class.\n */\nexport interface ClientCertificateCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n CredentialPersistenceOptions,\n AuthorityValidationOptions {\n /**\n * Option to include x5c header for SubjectName and Issuer name authorization.\n * Set this option to send base64 encoded public certificate in the client assertion header as an x5c claim\n */\n sendCertificateChain?: boolean;\n // TODO: Export again once we're ready to release this feature.\n // /**\n // * Specifies a regional authority. Please refer to the {@link RegionalAuthority} type for the accepted values.\n // * If {@link RegionalAuthority.AutoDiscoverRegion} is specified, we will try to discover the regional authority endpoint.\n // * If the property is not specified, the credential uses the global authority endpoint.\n // */\n // regionalAuthority?: string;\n}\n"]}

View File

@@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline";
import { credentialLogger, formatError, formatSuccess } from "../util/logging";
import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
import { IdentityClient } from "../client/identityClient";
import { getIdentityTokenEndpointSuffix } from "../util/identityTokenEndpoint";
import { tracingClient } from "../util/tracing";
const logger = credentialLogger("ClientSecretCredential");
// This credential is exported on browser bundles for development purposes.
// For this credential to work in browsers, browsers would need to have security features disabled.
// Please do not disable your browser security features.
/**
* Enables authentication to Microsoft Entra ID using a client secret
* that was generated for an App Registration. More information on how
* to configure a client secret can be found here:
*
* https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application
*
*/
export class ClientSecretCredential {
/**
* Creates an instance of the ClientSecretCredential with the details
* needed to authenticate against Microsoft Entra ID with a client
* secret.
*
* @param tenantId - The Microsoft Entra tenant (directory) ID.
* @param clientId - The client (application) ID of an App Registration in the tenant.
* @param clientSecret - A client secret that was generated for the App Registration.
* @param options - Options for configuring the client which makes the authentication request.
*/
constructor(tenantId, clientId, clientSecret, options) {
this.identityClient = new IdentityClient(options);
this.tenantId = tenantId;
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
this.clientId = clientId;
this.clientSecret = clientSecret;
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if
* successful. If authentication cannot be performed at this time, this method may
* return null. If an error occurs during authentication, an {@link AuthenticationError}
* containing failure details will be thrown.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(scopes, options = {}) {
return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
const tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds);
const query = new URLSearchParams({
response_type: "token",
grant_type: "client_credentials",
client_id: this.clientId,
client_secret: this.clientSecret,
scope: typeof scopes === "string" ? scopes : scopes.join(" "),
});
try {
const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);
const request = createPipelineRequest({
url: `${this.identityClient.authorityHost}/${tenantId}/${urlSuffix}`,
method: "POST",
body: query.toString(),
headers: createHttpHeaders({
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
}),
abortSignal: options && options.abortSignal,
tracingOptions: newOptions === null || newOptions === void 0 ? void 0 : newOptions.tracingOptions,
});
const tokenResponse = await this.identityClient.sendTokenRequest(request);
logger.getToken.info(formatSuccess(scopes));
return (tokenResponse && tokenResponse.accessToken) || null;
}
catch (err) {
logger.getToken.info(formatError(scopes, err));
throw err;
}
});
}
}
//# sourceMappingURL=clientSecretCredential.browser.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,60 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createMsalClient } from "../msal/nodeFlows/msalClient";
import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
import { CredentialUnavailableError } from "../errors";
import { credentialLogger } from "../util/logging";
import { ensureScopes } from "../util/scopeUtils";
import { tracingClient } from "../util/tracing";
const logger = credentialLogger("ClientSecretCredential");
/**
* Enables authentication to Microsoft Entra ID using a client secret
* that was generated for an App Registration. More information on how
* to configure a client secret can be found here:
*
* https://learn.microsoft.com/entra/identity-platform/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application
*
*/
export class ClientSecretCredential {
/**
* Creates an instance of the ClientSecretCredential with the details
* needed to authenticate against Microsoft Entra ID with a client
* secret.
*
* @param tenantId - The Microsoft Entra tenant (directory) ID.
* @param clientId - The client (application) ID of an App Registration in the tenant.
* @param clientSecret - A client secret that was generated for the App Registration.
* @param options - Options for configuring the client which makes the authentication request.
*/
constructor(tenantId, clientId, clientSecret, options = {}) {
if (!tenantId) {
throw new CredentialUnavailableError("ClientSecretCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.");
}
if (!clientId) {
throw new CredentialUnavailableError("ClientSecretCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.");
}
if (!clientSecret) {
throw new CredentialUnavailableError("ClientSecretCredential: clientSecret is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.");
}
this.clientSecret = clientSecret;
this.tenantId = tenantId;
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options }));
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(scopes, options = {}) {
return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger);
const arrayScopes = ensureScopes(scopes);
return this.msalClient.getTokenByClientSecret(arrayScopes, this.clientSecret, newOptions);
});
}
}
//# sourceMappingURL=clientSecretCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=clientSecretCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"clientSecretCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/clientSecretCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AuthorityValidationOptions } from \"./authorityValidationOptions\";\nimport { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Optional parameters for the {@link ClientSecretCredential} class.\n */\nexport interface ClientSecretCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n CredentialPersistenceOptions,\n AuthorityValidationOptions {\n // TODO: Export again once we're ready to release this feature.\n // /**\n // * Specifies a regional authority. Please refer to the {@link RegionalAuthority} type for the accepted values.\n // * If {@link RegionalAuthority.AutoDiscoverRegion} is specified, we will try to discover the regional authority endpoint.\n // * If the property is not specified, the credential uses the global authority endpoint.\n // */\n // regionalAuthority?: string;\n}\n"]}

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=credentialPersistenceOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"credentialPersistenceOptions.js","sourceRoot":"","sources":["../../../src/credentials/credentialPersistenceOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { TokenCachePersistenceOptions } from \"../msal/nodeFlows/tokenCachePersistenceOptions\";\n\n/**\n * Shared configuration options for credentials that support persistent token\n * caching.\n */\nexport interface CredentialPersistenceOptions {\n /**\n * Options to provide to the persistence layer (if one is available) when\n * storing credentials.\n *\n * You must first register a persistence provider plugin. See the\n * `@azure/identity-cache-persistence` package on NPM.\n *\n * Example:\n *\n * ```ts snippet:credential_persistence_options_example\n * import { useIdentityPlugin, DeviceCodeCredential } from \"@azure/identity\";\n *\n * useIdentityPlugin(cachePersistencePlugin);\n * const credential = new DeviceCodeCredential({\n * tokenCachePersistenceOptions: {\n * enabled: true,\n * },\n * });\n * ```\n */\n\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n}\n"]}

View File

@@ -0,0 +1,29 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
import { ChainedTokenCredential } from "./chainedTokenCredential";
const BrowserNotSupportedError = new Error("DefaultAzureCredential is not supported in the browser. Use InteractiveBrowserCredential instead.");
const logger = credentialLogger("DefaultAzureCredential");
/**
* Provides a default {@link ChainedTokenCredential} configuration for
* applications that will be deployed to Azure.
*
* Only available in Node.js.
*/
export class DefaultAzureCredential extends ChainedTokenCredential {
/**
* Creates an instance of the DefaultAzureCredential class.
*
* @param options - Options for configuring the client which makes the authentication request.
*/
constructor(_tokenCredentialOptions) {
super();
logger.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
getToken() {
logger.getToken.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
}
//# sourceMappingURL=defaultAzureCredential.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"defaultAzureCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/defaultAzureCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAGlE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,mGAAmG,CACpG,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,wBAAwB,CAAC,CAAC;AAE1D;;;;;GAKG;AACH,MAAM,OAAO,sBAAuB,SAAQ,sBAAsB;IAChE;;;;OAIG;IACH,YAAY,uBAAgD;QAC1D,KAAK,EAAE,CAAC;QACR,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,QAAQ;QACb,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { credentialLogger, formatError } from \"../util/logging\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { ChainedTokenCredential } from \"./chainedTokenCredential\";\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\n\nconst BrowserNotSupportedError = new Error(\n \"DefaultAzureCredential is not supported in the browser. Use InteractiveBrowserCredential instead.\",\n);\nconst logger = credentialLogger(\"DefaultAzureCredential\");\n\n/**\n * Provides a default {@link ChainedTokenCredential} configuration for\n * applications that will be deployed to Azure.\n *\n * Only available in Node.js.\n */\nexport class DefaultAzureCredential extends ChainedTokenCredential {\n /**\n * Creates an instance of the DefaultAzureCredential class.\n *\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(_tokenCredentialOptions?: TokenCredentialOptions) {\n super();\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public getToken(): Promise<AccessToken> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}

View File

@@ -0,0 +1,151 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { ManagedIdentityCredential, } from "./managedIdentityCredential";
import { AzureCliCredential } from "./azureCliCredential";
import { AzureDeveloperCliCredential } from "./azureDeveloperCliCredential";
import { AzurePowerShellCredential } from "./azurePowerShellCredential";
import { ChainedTokenCredential } from "./chainedTokenCredential";
import { EnvironmentCredential } from "./environmentCredential";
import { WorkloadIdentityCredential } from "./workloadIdentityCredential";
import { credentialLogger } from "../util/logging";
const logger = credentialLogger("DefaultAzureCredential");
/**
* Creates a {@link ManagedIdentityCredential} from the provided options.
* @param options - Options to configure the credential.
*
* @internal
*/
export function createDefaultManagedIdentityCredential(options = {}) {
var _a, _b, _c, _d;
(_a = options.retryOptions) !== null && _a !== void 0 ? _a : (options.retryOptions = {
maxRetries: 5,
retryDelayInMs: 800,
});
const managedIdentityClientId = (_b = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _b !== void 0 ? _b : process.env.AZURE_CLIENT_ID;
const workloadIdentityClientId = (_c = options === null || options === void 0 ? void 0 : options.workloadIdentityClientId) !== null && _c !== void 0 ? _c : managedIdentityClientId;
const managedResourceId = options === null || options === void 0 ? void 0 : options.managedIdentityResourceId;
const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;
const tenantId = (_d = options === null || options === void 0 ? void 0 : options.tenantId) !== null && _d !== void 0 ? _d : process.env.AZURE_TENANT_ID;
if (managedResourceId) {
const managedIdentityResourceIdOptions = Object.assign(Object.assign({}, options), { resourceId: managedResourceId });
return new ManagedIdentityCredential(managedIdentityResourceIdOptions);
}
if (workloadFile && workloadIdentityClientId) {
const workloadIdentityCredentialOptions = Object.assign(Object.assign({}, options), { tenantId: tenantId });
return new ManagedIdentityCredential(workloadIdentityClientId, workloadIdentityCredentialOptions);
}
if (managedIdentityClientId) {
const managedIdentityClientOptions = Object.assign(Object.assign({}, options), { clientId: managedIdentityClientId });
return new ManagedIdentityCredential(managedIdentityClientOptions);
}
// We may be able to return a UnavailableCredential here, but that may be a breaking change
return new ManagedIdentityCredential(options);
}
/**
* Creates a {@link WorkloadIdentityCredential} from the provided options.
* @param options - Options to configure the credential.
*
* @internal
*/
function createDefaultWorkloadIdentityCredential(options) {
var _a, _b, _c;
const managedIdentityClientId = (_a = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _a !== void 0 ? _a : process.env.AZURE_CLIENT_ID;
const workloadIdentityClientId = (_b = options === null || options === void 0 ? void 0 : options.workloadIdentityClientId) !== null && _b !== void 0 ? _b : managedIdentityClientId;
const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;
const tenantId = (_c = options === null || options === void 0 ? void 0 : options.tenantId) !== null && _c !== void 0 ? _c : process.env.AZURE_TENANT_ID;
if (workloadFile && workloadIdentityClientId) {
const workloadIdentityCredentialOptions = Object.assign(Object.assign({}, options), { tenantId, clientId: workloadIdentityClientId, tokenFilePath: workloadFile });
return new WorkloadIdentityCredential(workloadIdentityCredentialOptions);
}
if (tenantId) {
const workloadIdentityClientTenantOptions = Object.assign(Object.assign({}, options), { tenantId });
return new WorkloadIdentityCredential(workloadIdentityClientTenantOptions);
}
// We may be able to return a UnavailableCredential here, but that may be a breaking change
return new WorkloadIdentityCredential(options);
}
/**
* Creates a {@link AzureDeveloperCliCredential} from the provided options.
* @param options - Options to configure the credential.
*
* @internal
*/
function createDefaultAzureDeveloperCliCredential(options = {}) {
const processTimeoutInMs = options.processTimeoutInMs;
return new AzureDeveloperCliCredential(Object.assign({ processTimeoutInMs }, options));
}
/**
* Creates a {@link AzureCliCredential} from the provided options.
* @param options - Options to configure the credential.
*
* @internal
*/
function createDefaultAzureCliCredential(options = {}) {
const processTimeoutInMs = options.processTimeoutInMs;
return new AzureCliCredential(Object.assign({ processTimeoutInMs }, options));
}
/**
* Creates a {@link AzurePowerShellCredential} from the provided options.
* @param options - Options to configure the credential.
*
* @internal
*/
function createDefaultAzurePowershellCredential(options = {}) {
const processTimeoutInMs = options.processTimeoutInMs;
return new AzurePowerShellCredential(Object.assign({ processTimeoutInMs }, options));
}
/**
* Creates an {@link EnvironmentCredential} from the provided options.
* @param options - Options to configure the credential.
*
* @internal
*/
export function createEnvironmentCredential(options = {}) {
return new EnvironmentCredential(options);
}
/**
* A no-op credential that logs the reason it was skipped if getToken is called.
* @internal
*/
export class UnavailableDefaultCredential {
constructor(credentialName, message) {
this.credentialName = credentialName;
this.credentialUnavailableErrorMessage = message;
}
getToken() {
logger.getToken.info(`Skipping ${this.credentialName}, reason: ${this.credentialUnavailableErrorMessage}`);
return Promise.resolve(null);
}
}
/**
* Provides a default {@link ChainedTokenCredential} configuration that should
* work for most applications that use the Azure SDK.
*/
export class DefaultAzureCredential extends ChainedTokenCredential {
constructor(options) {
const credentialFunctions = [
createEnvironmentCredential,
createDefaultWorkloadIdentityCredential,
createDefaultManagedIdentityCredential,
createDefaultAzureCliCredential,
createDefaultAzurePowershellCredential,
createDefaultAzureDeveloperCliCredential,
];
// DefaultCredential constructors should not throw, instead throwing on getToken() which is handled by ChainedTokenCredential.
// When adding new credentials to the default chain, consider:
// 1. Making the constructor parameters required and explicit
// 2. Validating any required parameters in the factory function
// 3. Returning a UnavailableDefaultCredential from the factory function if a credential is unavailable for any reason
const credentials = credentialFunctions.map((createCredentialFn) => {
try {
return createCredentialFn(options);
}
catch (err) {
logger.warning(`Skipped ${createCredentialFn.name} because of an error creating the credential: ${err}`);
return new UnavailableDefaultCredential(createCredentialFn.name, err.message);
}
});
super(...credentials);
}
}
//# sourceMappingURL=defaultAzureCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=defaultAzureCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"defaultAzureCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/defaultAzureCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AuthorityValidationOptions } from \"./authorityValidationOptions\";\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Provides options to configure the {@link DefaultAzureCredential} class.\n * This variation supports `managedIdentityClientId` and not `managedIdentityResourceId`, since only one of both is supported.\n */\nexport interface DefaultAzureCredentialClientIdOptions extends DefaultAzureCredentialOptions {\n /**\n * Optionally pass in a user assigned client ID to be used by the {@link ManagedIdentityCredential}.\n * This client ID can also be passed through to the {@link ManagedIdentityCredential} through the environment variable: AZURE_CLIENT_ID.\n */\n managedIdentityClientId?: string;\n /**\n * Optionally pass in a user assigned client ID to be used by the {@link WorkloadIdentityCredential}.\n * This client ID can also be passed through to the {@link WorkloadIdentityCredential} through the environment variable: AZURE_CLIENT_ID.\n */\n workloadIdentityClientId?: string;\n}\n\n/**\n * Provides options to configure the {@link DefaultAzureCredential} class.\n * This variation supports `managedIdentityResourceId` and not `managedIdentityClientId`, since only one of both is supported.\n */\nexport interface DefaultAzureCredentialResourceIdOptions extends DefaultAzureCredentialOptions {\n /**\n * Optionally pass in a resource ID to be used by the {@link ManagedIdentityCredential}.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n managedIdentityResourceId: string;\n}\n\n/**\n * Provides options to configure the {@link DefaultAzureCredential} class.\n */\nexport interface DefaultAzureCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n AuthorityValidationOptions {\n /**\n * Optionally pass in a Tenant ID to be used as part of the credential.\n * By default it may use a generic tenant ID depending on the underlying credential.\n */\n tenantId?: string;\n\n /**\n * Timeout configurable for making token requests for developer credentials, namely, {@link AzurePowershellCredential},\n * {@link AzureDeveloperCliCredential} and {@link AzureCliCredential}.\n * Process timeout for credentials should be provided in milliseconds.\n */\n processTimeoutInMs?: number;\n}\n"]}

View File

@@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
const BrowserNotSupportedError = new Error("DeviceCodeCredential is not supported in the browser.");
const logger = credentialLogger("DeviceCodeCredential");
/**
* Enables authentication to Microsoft Entra ID using a device code
* that the user can enter into https://microsoft.com/devicelogin.
*/
export class DeviceCodeCredential {
/**
* Only available in Node.js
*/
constructor() {
logger.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
getToken() {
logger.getToken.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
}
//# sourceMappingURL=deviceCodeCredential.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"deviceCodeCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/deviceCodeCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;AACpG,MAAM,MAAM,GAAG,gBAAgB,CAAC,sBAAsB,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAM,OAAO,oBAAoB;IAC/B;;OAEG;IACH;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,QAAQ;QACb,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\n\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\"DeviceCodeCredential is not supported in the browser.\");\nconst logger = credentialLogger(\"DeviceCodeCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID using a device code\n * that the user can enter into https://microsoft.com/devicelogin.\n */\nexport class DeviceCodeCredential implements TokenCredential {\n /**\n * Only available in Node.js\n */\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}

View File

@@ -0,0 +1,91 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, resolveTenantId, } from "../util/tenantIdUtils";
import { credentialLogger } from "../util/logging";
import { ensureScopes } from "../util/scopeUtils";
import { tracingClient } from "../util/tracing";
import { createMsalClient } from "../msal/nodeFlows/msalClient";
import { DeveloperSignOnClientId } from "../constants";
const logger = credentialLogger("DeviceCodeCredential");
/**
* Method that logs the user code from the DeviceCodeCredential.
* @param deviceCodeInfo - The device code.
*/
export function defaultDeviceCodePromptCallback(deviceCodeInfo) {
console.log(deviceCodeInfo.message);
}
/**
* Enables authentication to Microsoft Entra ID using a device code
* that the user can enter into https://microsoft.com/devicelogin.
*/
export class DeviceCodeCredential {
/**
* Creates an instance of DeviceCodeCredential with the details needed
* to initiate the device code authorization flow with Microsoft Entra ID.
*
* A message will be logged, giving users a code that they can use to authenticate once they go to https://microsoft.com/devicelogin
*
* Developers can configure how this message is shown by passing a custom `userPromptCallback`:
*
* ```ts snippet:device_code_credential_example
* import { DeviceCodeCredential } from "@azure/identity";
*
* const credential = new DeviceCodeCredential({
* tenantId: process.env.AZURE_TENANT_ID,
* clientId: process.env.AZURE_CLIENT_ID,
* userPromptCallback: (info) => {
* console.log("CUSTOMIZED PROMPT CALLBACK", info.message);
* },
* });
* ```
*
* @param options - Options for configuring the client which makes the authentication requests.
*/
constructor(options) {
var _a, _b;
this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId;
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
const clientId = (_a = options === null || options === void 0 ? void 0 : options.clientId) !== null && _a !== void 0 ? _a : DeveloperSignOnClientId;
const tenantId = resolveTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId, clientId);
this.userPromptCallback = (_b = options === null || options === void 0 ? void 0 : options.userPromptCallback) !== null && _b !== void 0 ? _b : defaultDeviceCodePromptCallback;
this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options || {} }));
this.disableAutomaticAuthentication = options === null || options === void 0 ? void 0 : options.disableAutomaticAuthentication;
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* If the user provided the option `disableAutomaticAuthentication`,
* once the token can't be retrieved silently,
* this method won't attempt to request user interaction to retrieve the token.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(scopes, options = {}) {
return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger);
const arrayScopes = ensureScopes(scopes);
return this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication }));
});
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* If the token can't be retrieved silently, this method will always generate a challenge for the user.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async authenticate(scopes, options = {}) {
return tracingClient.withSpan(`${this.constructor.name}.authenticate`, options, async (newOptions) => {
const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
await this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: false }));
return this.msalClient.getActiveAccount();
});
}
}
//# sourceMappingURL=deviceCodeCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=deviceCodeCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"deviceCodeCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/deviceCodeCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport { InteractiveCredentialOptions } from \"./interactiveCredentialOptions\";\n\n/**\n * Provides the user code and verification URI where the code must be\n * entered. Also provides a message to display to the user which\n * contains an instruction with these details.\n */\nexport interface DeviceCodeInfo {\n /**\n * The device code that the user must enter into the verification page.\n */\n userCode: string;\n\n /**\n * The verification URI to which the user must navigate to enter the device\n * code.\n */\n verificationUri: string;\n\n /**\n * A message that may be shown to the user to instruct them on how to enter\n * the device code in the page specified by the verification URI.\n */\n message: string;\n}\n\n/**\n * Defines the signature of a callback which will be passed to\n * DeviceCodeCredential for the purpose of displaying authentication\n * details to the user.\n */\nexport type DeviceCodePromptCallback = (deviceCodeInfo: DeviceCodeInfo) => void;\n\n/**\n * Defines options for the InteractiveBrowserCredential class for Node.js.\n */\nexport interface DeviceCodeCredentialOptions\n extends InteractiveCredentialOptions,\n CredentialPersistenceOptions {\n /**\n * The Microsoft Entra tenant (directory) ID.\n */\n tenantId?: string;\n /**\n * Client ID of the Microsoft Entra application that users will sign into.\n * It is recommended that developers register their applications and assign appropriate roles.\n * For more information, visit https://aka.ms/identity/AppRegistrationAndRoleAssignment.\n * If not specified, users will authenticate to an Azure development application,\n * which is not recommended for production scenarios.\n */\n clientId?: string;\n /**\n * A callback function that will be invoked to show {@link DeviceCodeInfo} to the user.\n * If left unassigned, we will automatically log the device code information\n * and the authentication instructions in the console.\n */\n userPromptCallback?: DeviceCodePromptCallback;\n}\n"]}

View File

@@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
const BrowserNotSupportedError = new Error("EnvironmentCredential is not supported in the browser.");
const logger = credentialLogger("EnvironmentCredential");
/**
* Enables authentication to Microsoft Entra ID using client secret
* details configured in environment variables
*/
export class EnvironmentCredential {
/**
* Only available in Node.js
*/
constructor() {
logger.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
getToken() {
logger.getToken.info(formatError("", BrowserNotSupportedError));
throw BrowserNotSupportedError;
}
}
//# sourceMappingURL=environmentCredential.browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"environmentCredential.browser.js","sourceRoot":"","sources":["../../../src/credentials/environmentCredential.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,wDAAwD,CACzD,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,uBAAuB,CAAC,CAAC;AAEzD;;;GAGG;AACH,MAAM,OAAO,qBAAqB;IAChC;;OAEG;IACH;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAED,QAAQ;QACN,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError } from \"../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"EnvironmentCredential is not supported in the browser.\",\n);\nconst logger = credentialLogger(\"EnvironmentCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID using client secret\n * details configured in environment variables\n */\nexport class EnvironmentCredential implements TokenCredential {\n /**\n * Only available in Node.js\n */\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}

View File

@@ -0,0 +1,130 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { AuthenticationError, CredentialUnavailableError } from "../errors";
import { credentialLogger, formatError, formatSuccess, processEnvVars } from "../util/logging";
import { ClientCertificateCredential } from "./clientCertificateCredential";
import { ClientSecretCredential } from "./clientSecretCredential";
import { UsernamePasswordCredential } from "./usernamePasswordCredential";
import { checkTenantId } from "../util/tenantIdUtils";
import { tracingClient } from "../util/tracing";
/**
* Contains the list of all supported environment variable names so that an
* appropriate error message can be generated when no credentials can be
* configured.
*
* @internal
*/
export const AllSupportedEnvironmentVariables = [
"AZURE_TENANT_ID",
"AZURE_CLIENT_ID",
"AZURE_CLIENT_SECRET",
"AZURE_CLIENT_CERTIFICATE_PATH",
"AZURE_CLIENT_CERTIFICATE_PASSWORD",
"AZURE_USERNAME",
"AZURE_PASSWORD",
"AZURE_ADDITIONALLY_ALLOWED_TENANTS",
"AZURE_CLIENT_SEND_CERTIFICATE_CHAIN",
];
function getAdditionallyAllowedTenants() {
var _a;
const additionallyAllowedValues = (_a = process.env.AZURE_ADDITIONALLY_ALLOWED_TENANTS) !== null && _a !== void 0 ? _a : "";
return additionallyAllowedValues.split(";");
}
const credentialName = "EnvironmentCredential";
const logger = credentialLogger(credentialName);
export function getSendCertificateChain() {
var _a;
const sendCertificateChain = ((_a = process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN) !== null && _a !== void 0 ? _a : "").toLowerCase();
const result = sendCertificateChain === "true" || sendCertificateChain === "1";
logger.verbose(`AZURE_CLIENT_SEND_CERTIFICATE_CHAIN: ${process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN}; sendCertificateChain: ${result}`);
return result;
}
/**
* Enables authentication to Microsoft Entra ID using a client secret or certificate, or as a user
* with a username and password.
*/
export class EnvironmentCredential {
/**
* Creates an instance of the EnvironmentCredential class and decides what credential to use depending on the available environment variables.
*
* Required environment variables:
* - `AZURE_TENANT_ID`: The Microsoft Entra tenant (directory) ID.
* - `AZURE_CLIENT_ID`: The client (application) ID of an App Registration in the tenant.
*
* If setting the AZURE_TENANT_ID, then you can also set the additionally allowed tenants
* - `AZURE_ADDITIONALLY_ALLOWED_TENANTS`: For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens with a single semicolon delimited string. Use * to allow all tenants.
*
* Environment variables used for client credential authentication:
* - `AZURE_CLIENT_SECRET`: A client secret that was generated for the App Registration.
* - `AZURE_CLIENT_CERTIFICATE_PATH`: The path to a PEM certificate to use during the authentication, instead of the client secret.
* - `AZURE_CLIENT_CERTIFICATE_PASSWORD`: (optional) password for the certificate file.
* - `AZURE_CLIENT_SEND_CERTIFICATE_CHAIN`: (optional) indicates that the certificate chain should be set in x5c header to support subject name / issuer based authentication.
*
* Alternatively, users can provide environment variables for username and password authentication:
* - `AZURE_USERNAME`: Username to authenticate with.
* - `AZURE_PASSWORD`: Password to authenticate with.
*
* If the environment variables required to perform the authentication are missing, a {@link CredentialUnavailableError} will be thrown.
* If the authentication fails, or if there's an unknown error, an {@link AuthenticationError} will be thrown.
*
* @param options - Options for configuring the client which makes the authentication request.
*/
constructor(options) {
// Keep track of any missing environment variables for error details
this._credential = undefined;
const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(", ");
logger.info(`Found the following environment variables: ${assigned}`);
const tenantId = process.env.AZURE_TENANT_ID, clientId = process.env.AZURE_CLIENT_ID, clientSecret = process.env.AZURE_CLIENT_SECRET;
const additionallyAllowedTenantIds = getAdditionallyAllowedTenants();
const sendCertificateChain = getSendCertificateChain();
const newOptions = Object.assign(Object.assign({}, options), { additionallyAllowedTenantIds, sendCertificateChain });
if (tenantId) {
checkTenantId(logger, tenantId);
}
if (tenantId && clientId && clientSecret) {
logger.info(`Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`);
this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, newOptions);
return;
}
const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH;
const certificatePassword = process.env.AZURE_CLIENT_CERTIFICATE_PASSWORD;
if (tenantId && clientId && certificatePath) {
logger.info(`Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`);
this._credential = new ClientCertificateCredential(tenantId, clientId, { certificatePath, certificatePassword }, newOptions);
return;
}
const username = process.env.AZURE_USERNAME;
const password = process.env.AZURE_PASSWORD;
if (tenantId && clientId && username && password) {
logger.info(`Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`);
this._credential = new UsernamePasswordCredential(tenantId, clientId, username, password, newOptions);
}
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - Optional parameters. See {@link GetTokenOptions}.
*/
async getToken(scopes, options = {}) {
return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {
if (this._credential) {
try {
const result = await this._credential.getToken(scopes, newOptions);
logger.getToken.info(formatSuccess(scopes));
return result;
}
catch (err) {
const authenticationError = new AuthenticationError(400, {
error: `${credentialName} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,
error_description: err.message.toString().split("More details:").join(""),
});
logger.getToken.info(formatError(scopes, authenticationError));
throw authenticationError;
}
}
throw new CredentialUnavailableError(`${credentialName} is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`);
});
}
}
//# sourceMappingURL=environmentCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=environmentCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"environmentCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/environmentCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AuthorityValidationOptions } from \"./authorityValidationOptions\";\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Enables authentication to Microsoft Entra ID depending on the available environment variables.\n * Defines options for the EnvironmentCredential class.\n */\nexport interface EnvironmentCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n AuthorityValidationOptions {}\n"]}

View File

@@ -0,0 +1,86 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { credentialLogger, formatError } from "../util/logging";
import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
import { MSALAuthCode } from "../msal/browserFlows/msalAuthCode";
import { ensureScopes } from "../util/scopeUtils";
import { tracingClient } from "../util/tracing";
const logger = credentialLogger("InteractiveBrowserCredential");
/**
* Enables authentication to Microsoft Entra ID inside of the web browser
* using the interactive login flow.
*/
export class InteractiveBrowserCredential {
/**
* Creates an instance of the InteractiveBrowserCredential with the
* details needed to authenticate against Microsoft Entra ID with
* a user identity.
*
* This credential uses the [Authorization Code Flow](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow).
* On Node.js, it will open a browser window while it listens for a redirect response from the authentication service.
* On browsers, it authenticates via popups. The `loginStyle` optional parameter can be set to `redirect` to authenticate by redirecting the user to an Azure secure login page, which then will redirect the user back to the web application where the authentication started.
*
* It's recommended that the Microsoft Entra Applications used are configured to authenticate using Single Page Applications.
* More information here: [link](https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-spa-app-registration#redirect-uri-msaljs-20-with-auth-code-flow).
*
* @param options - Options for configuring the client which makes the authentication request.
*/
constructor(options) {
if (!(options === null || options === void 0 ? void 0 : options.clientId)) {
const error = new Error("The parameter `clientId` cannot be left undefined for the `InteractiveBrowserCredential`");
logger.info(formatError("", error));
throw error;
}
this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId;
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
const browserOptions = options;
const loginStyle = browserOptions.loginStyle || "popup";
const loginStyles = ["redirect", "popup"];
if (loginStyles.indexOf(loginStyle) === -1) {
const error = new Error(`Invalid loginStyle: ${browserOptions.loginStyle}. Should be any of the following: ${loginStyles.join(", ")}.`);
logger.info(formatError("", error));
throw error;
}
const msalOptions = Object.assign(Object.assign({}, options), { tokenCredentialOptions: options, logger, loginStyle: loginStyle, redirectUri: typeof options.redirectUri === "function" ? options.redirectUri() : options.redirectUri });
this.msalFlow = new MSALAuthCode(msalOptions);
this.disableAutomaticAuthentication = options === null || options === void 0 ? void 0 : options.disableAutomaticAuthentication;
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* If the user provided the option `disableAutomaticAuthentication`,
* once the token can't be retrieved silently,
* this method won't attempt to request user interaction to retrieve the token.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(scopes, options = {}) {
return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
const tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds);
newOptions.tenantId = tenantId;
const arrayScopes = ensureScopes(scopes);
return this.msalFlow.getToken(arrayScopes, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication }));
});
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* If the token can't be retrieved silently, this method will require user interaction to retrieve the token.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async authenticate(scopes, options = {}) {
return tracingClient.withSpan(`${this.constructor.name}.authenticate`, options, async (newOptions) => {
const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
await this.msalFlow.getToken(arrayScopes, newOptions);
return this.msalFlow.getActiveAccount();
});
}
}
//# sourceMappingURL=interactiveBrowserCredential.browser.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,91 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, resolveTenantId, } from "../util/tenantIdUtils";
import { credentialLogger } from "../util/logging";
import { ensureScopes } from "../util/scopeUtils";
import { tracingClient } from "../util/tracing";
import { createMsalClient } from "../msal/nodeFlows/msalClient";
import { DeveloperSignOnClientId } from "../constants";
const logger = credentialLogger("InteractiveBrowserCredential");
/**
* Enables authentication to Microsoft Entra ID inside of the web browser
* using the interactive login flow.
*/
export class InteractiveBrowserCredential {
/**
* Creates an instance of InteractiveBrowserCredential with the details needed.
*
* This credential uses the [Authorization Code Flow](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow).
* On Node.js, it will open a browser window while it listens for a redirect response from the authentication service.
* On browsers, it authenticates via popups. The `loginStyle` optional parameter can be set to `redirect` to authenticate by redirecting the user to an Azure secure login page, which then will redirect the user back to the web application where the authentication started.
*
* For Node.js, if a `clientId` is provided, the Microsoft Entra application will need to be configured to have a "Mobile and desktop applications" redirect endpoint.
* Follow our guide on [setting up Redirect URIs for Desktop apps that calls to web APIs](https://learn.microsoft.com/entra/identity-platform/scenario-desktop-app-registration#redirect-uris).
*
* @param options - Options for configuring the client which makes the authentication requests.
*/
constructor(options) {
var _a, _b, _c, _d, _e;
this.tenantId = resolveTenantId(logger, options.tenantId, options.clientId);
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
const msalClientOptions = Object.assign(Object.assign({}, options), { tokenCredentialOptions: options, logger });
const ibcNodeOptions = options;
this.browserCustomizationOptions = ibcNodeOptions.browserCustomizationOptions;
this.loginHint = ibcNodeOptions.loginHint;
if ((_a = ibcNodeOptions === null || ibcNodeOptions === void 0 ? void 0 : ibcNodeOptions.brokerOptions) === null || _a === void 0 ? void 0 : _a.enabled) {
if (!((_b = ibcNodeOptions === null || ibcNodeOptions === void 0 ? void 0 : ibcNodeOptions.brokerOptions) === null || _b === void 0 ? void 0 : _b.parentWindowHandle)) {
throw new Error("In order to do WAM authentication, `parentWindowHandle` under `brokerOptions` is a required parameter");
}
else {
msalClientOptions.brokerOptions = {
enabled: true,
parentWindowHandle: ibcNodeOptions.brokerOptions.parentWindowHandle,
legacyEnableMsaPassthrough: (_c = ibcNodeOptions.brokerOptions) === null || _c === void 0 ? void 0 : _c.legacyEnableMsaPassthrough,
useDefaultBrokerAccount: (_d = ibcNodeOptions.brokerOptions) === null || _d === void 0 ? void 0 : _d.useDefaultBrokerAccount,
};
}
}
this.msalClient = createMsalClient((_e = options.clientId) !== null && _e !== void 0 ? _e : DeveloperSignOnClientId, this.tenantId, msalClientOptions);
this.disableAutomaticAuthentication = options === null || options === void 0 ? void 0 : options.disableAutomaticAuthentication;
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* If the user provided the option `disableAutomaticAuthentication`,
* once the token can't be retrieved silently,
* this method won't attempt to request user interaction to retrieve the token.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(scopes, options = {}) {
return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger);
const arrayScopes = ensureScopes(scopes);
return this.msalClient.getTokenByInteractiveRequest(arrayScopes, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication, browserCustomizationOptions: this.browserCustomizationOptions, loginHint: this.loginHint }));
});
}
/**
* Authenticates with Microsoft Entra ID and returns an access token if successful.
* If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
*
* If the token can't be retrieved silently, this method will always generate a challenge for the user.
*
* On Node.js, this credential has [Proof Key for Code Exchange (PKCE)](https://datatracker.ietf.org/doc/html/rfc7636) enabled by default.
* PKCE is a security feature that mitigates authentication code interception attacks.
*
* @param scopes - The list of scopes for which the token will have access.
* @param options - The options used to configure any requests this
* TokenCredential implementation might make.
*/
async authenticate(scopes, options = {}) {
return tracingClient.withSpan(`${this.constructor.name}.authenticate`, options, async (newOptions) => {
const arrayScopes = ensureScopes(scopes);
await this.msalClient.getTokenByInteractiveRequest(arrayScopes, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: false, browserCustomizationOptions: this.browserCustomizationOptions, loginHint: this.loginHint }));
return this.msalClient.getActiveAccount();
});
}
}
//# sourceMappingURL=interactiveBrowserCredential.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=interactiveBrowserCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"interactiveBrowserCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/interactiveBrowserCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { BrowserCustomizationOptions } from \"./browserCustomizationOptions\";\nimport { BrokerAuthOptions } from \"./brokerAuthOptions\";\nimport { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport { InteractiveCredentialOptions } from \"./interactiveCredentialOptions\";\n\n/**\n * (Browser-only feature)\n * The \"login style\" to use in the authentication flow:\n * - \"redirect\" redirects the user to the authentication page and then\n * redirects them back to the page once authentication is completed.\n * - \"popup\" opens a new browser window through with the redirect flow\n * is initiated. The user's existing browser window does not leave\n * the current page\n */\nexport type BrowserLoginStyle = \"redirect\" | \"popup\";\n\n/**\n * Defines the common options for the InteractiveBrowserCredential class.\n */\nexport interface InteractiveBrowserCredentialNodeOptions\n extends InteractiveCredentialOptions,\n CredentialPersistenceOptions,\n BrowserCustomizationOptions,\n BrokerAuthOptions {\n /**\n * Gets the redirect URI of the application. This should be same as the value\n * in the application registration portal. Defaults to `window.location.href`.\n * This field is no longer required for Node.js.\n */\n redirectUri?: string | (() => string);\n\n /**\n * The Microsoft Entra tenant (directory) ID.\n */\n tenantId?: string;\n\n /**\n * The Client ID of the Microsoft Entra application that users will sign into.\n * It is recommended that developers register their applications and assign appropriate roles.\n * For more information, visit https://aka.ms/identity/AppRegistrationAndRoleAssignment.\n * If not specified, users will authenticate to an Azure development application,\n * which is not recommended for production scenarios.\n */\n clientId?: string;\n\n /**\n * loginHint allows a user name to be pre-selected for interactive logins.\n * Setting this option skips the account selection prompt and immediately attempts to login with the specified account.\n */\n loginHint?: string;\n}\n\n/**\n * Defines the common options for the InteractiveBrowserCredential class.\n */\nexport interface InteractiveBrowserCredentialInBrowserOptions extends InteractiveCredentialOptions {\n /**\n * Gets the redirect URI of the application. This should be same as the value\n * in the application registration portal. Defaults to `window.location.href`.\n * This field is no longer required for Node.js.\n */\n redirectUri?: string | (() => string);\n\n /**\n * The Microsoft Entra tenant (directory) ID.\n */\n tenantId?: string;\n\n /**\n * The Client ID of the Microsoft Entra application that users will sign into.\n * This parameter is required on the browser.\n * Developers need to register their applications and assign appropriate roles.\n * For more information, visit https://aka.ms/identity/AppRegistrationAndRoleAssignment.\n */\n clientId: string;\n\n /**\n * Specifies whether a redirect or a popup window should be used to\n * initiate the user authentication flow. Possible values are \"redirect\"\n * or \"popup\" (default) for browser and \"popup\" (default) for node.\n *\n */\n loginStyle?: BrowserLoginStyle;\n\n /**\n * loginHint allows a user name to be pre-selected for interactive logins.\n * Setting this option skips the account selection prompt and immediately attempts to login with the specified account.\n */\n loginHint?: string;\n}\n"]}

View File

@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=interactiveCredentialOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"interactiveCredentialOptions.js","sourceRoot":"","sources":["../../../src/credentials/interactiveCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AuthenticationRecord } from \"../msal/types\";\nimport { AuthorityValidationOptions } from \"./authorityValidationOptions\";\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Common constructor options for the Identity credentials that requires user interaction.\n */\nexport interface InteractiveCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n AuthorityValidationOptions {\n /**\n * Result of a previous authentication that can be used to retrieve the cached credentials of each individual account.\n * This is necessary to provide in case the application wants to work with more than one account per\n * Client ID and Tenant ID pair.\n *\n * This record can be retrieved by calling to the credential's `authenticate()` method, as follows:\n *\n * const authenticationRecord = await credential.authenticate();\n *\n */\n authenticationRecord?: AuthenticationRecord;\n\n /**\n * Makes getToken throw if a manual authentication is necessary.\n * Developers will need to call to `authenticate()` to control when to manually authenticate.\n */\n disableAutomaticAuthentication?: boolean;\n}\n"]}

View File

@@ -0,0 +1,71 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createHttpHeaders, createPipelineRequest, } from "@azure/core-rest-pipeline";
import { credentialLogger } from "../../util/logging";
import { mapScopesToResource } from "./utils";
const msiName = "ManagedIdentityCredential - AppServiceMSI 2017";
const logger = credentialLogger(msiName);
/**
* Generates the options used on the request for an access token.
*/
function prepareRequestOptions(scopes, clientId) {
const resource = mapScopesToResource(scopes);
if (!resource) {
throw new Error(`${msiName}: Multiple scopes are not supported.`);
}
const queryParameters = {
resource,
"api-version": "2017-09-01",
};
if (clientId) {
queryParameters.clientid = clientId;
}
const query = new URLSearchParams(queryParameters);
// This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.
if (!process.env.MSI_ENDPOINT) {
throw new Error(`${msiName}: Missing environment variable: MSI_ENDPOINT`);
}
if (!process.env.MSI_SECRET) {
throw new Error(`${msiName}: Missing environment variable: MSI_SECRET`);
}
return {
url: `${process.env.MSI_ENDPOINT}?${query.toString()}`,
method: "GET",
headers: createHttpHeaders({
Accept: "application/json",
secret: process.env.MSI_SECRET,
}),
};
}
/**
* Defines how to determine whether the Azure App Service MSI is available, and also how to retrieve a token from the Azure App Service MSI.
*/
export const appServiceMsi2017 = {
name: "appServiceMsi2017",
async isAvailable({ scopes }) {
const resource = mapScopesToResource(scopes);
if (!resource) {
logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
return false;
}
const env = process.env;
const result = Boolean(env.MSI_ENDPOINT && env.MSI_SECRET);
if (!result) {
logger.info(`${msiName}: Unavailable. The environment variables needed are: MSI_ENDPOINT and MSI_SECRET.`);
}
return result;
},
async getToken(configuration, getTokenOptions = {}) {
const { identityClient, scopes, clientId, resourceId } = configuration;
if (resourceId) {
logger.warning(`${msiName}: managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
}
logger.info(`${msiName}: Using the endpoint and the secret coming form the environment variables: MSI_ENDPOINT=${process.env.MSI_ENDPOINT} and MSI_SECRET=[REDACTED].`);
const request = createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId)), {
// Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
allowInsecureConnection: true }));
const tokenResponse = await identityClient.sendTokenRequest(request);
return (tokenResponse && tokenResponse.accessToken) || null;
},
};
//# sourceMappingURL=appServiceMsi2017.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,71 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createHttpHeaders, createPipelineRequest, } from "@azure/core-rest-pipeline";
import { credentialLogger } from "../../util/logging";
import { mapScopesToResource } from "./utils";
const msiName = "ManagedIdentityCredential - AppServiceMSI 2019";
const logger = credentialLogger(msiName);
/**
* Generates the options used on the request for an access token.
*/
function prepareRequestOptions(scopes, clientId, resourceId) {
const resource = mapScopesToResource(scopes);
if (!resource) {
throw new Error(`${msiName}: Multiple scopes are not supported.`);
}
const queryParameters = {
resource,
"api-version": "2019-08-01",
};
if (clientId) {
queryParameters.client_id = clientId;
}
if (resourceId) {
queryParameters.mi_res_id = resourceId;
}
const query = new URLSearchParams(queryParameters);
// This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.
if (!process.env.IDENTITY_ENDPOINT) {
throw new Error(`${msiName}: Missing environment variable: IDENTITY_ENDPOINT`);
}
if (!process.env.IDENTITY_HEADER) {
throw new Error(`${msiName}: Missing environment variable: IDENTITY_HEADER`);
}
return {
url: `${process.env.IDENTITY_ENDPOINT}?${query.toString()}`,
method: "GET",
headers: createHttpHeaders({
Accept: "application/json",
"X-IDENTITY-HEADER": process.env.IDENTITY_HEADER,
}),
};
}
/**
* Defines how to determine whether the Azure App Service MSI is available, and also how to retrieve a token from the Azure App Service MSI.
*/
export const appServiceMsi2019 = {
name: "appServiceMsi2019",
async isAvailable({ scopes }) {
const resource = mapScopesToResource(scopes);
if (!resource) {
logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
return false;
}
const env = process.env;
const result = Boolean(env.IDENTITY_ENDPOINT && env.IDENTITY_HEADER);
if (!result) {
logger.info(`${msiName}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT and IDENTITY_HEADER.`);
}
return result;
},
async getToken(configuration, getTokenOptions = {}) {
const { identityClient, scopes, clientId, resourceId } = configuration;
logger.info(`${msiName}: Using the endpoint and the secret coming form the environment variables: IDENTITY_ENDPOINT=${process.env.IDENTITY_ENDPOINT} and IDENTITY_HEADER=[REDACTED].`);
const request = createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId, resourceId)), {
// Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
allowInsecureConnection: true }));
const tokenResponse = await identityClient.sendTokenRequest(request);
return (tokenResponse && tokenResponse.accessToken) || null;
},
};
//# sourceMappingURL=appServiceMsi2019.js.map

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More