Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@browserstack/identity

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@browserstack/identity

Provides credential implementations for Azure SDK libraries that can authenticate with Azure Active Directory

  • 3.3.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

Azure Identity client library for JavaScript

NOTE: This is a patched version to support node v20

The Azure Identity library provides Azure Active Directory (Azure AD) token authentication through a set of convenient TokenCredential implementations.

For examples of various credentials, see the Azure Identity examples page.

Key links:

Getting started

Migrate from v1 to v2 of @azure/identity

If you're using v1 of @azure/identity, see the migration guide to update to v2.

Currently supported environments

  • LTS versions of Node.js
    • Note: If your application runs on Node.js v8 or lower and you cannot upgrade your Node.js version to latest stable version, then pin your @azure/identity dependency to version 1.1.0.
  • Latest versions of Safari, Chrome, Edge, and Firefox.
    • Note: Among the different credentials exported in this library, InteractiveBrowserCredential is the only one that is supported in the browser.

See our support policy for more details.

Install the package

Install Azure Identity with npm:

npm install --save @azure/identity

Prerequisites

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 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). Specifically, we use the v2 MSAL.js libraries, which use OAuth 2.0 Authorization Code Flow with PKCE and are OpenID-compliant. While @azure/identity focuses on simplicity, the MSAL.js libraries, such as @azure/msal-common, @azure/msal-node, and @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's TokenCredential class. In principle, any object with a getToken method that satisfies getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken | null> will work 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.

Though our credential types support many advanced cases, developers may want full control of the authentication protocol. For that use case, we recommend using Microsoft Authentication Library for JavaScript (MSAL.js) directly. You can read more through the following links:

For advanced authentication workflows in the browser, we have a section where we showcase how to use the @azure/msal-browser library directly to authenticate Azure SDK clients.

Authenticate the client in development environment

While we recommend using managed identity or service principal authentication in your production application, it is 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 which 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 will launch the browser to authenticate the user.

For systems without a default web browser, the azd auth login --use-device-code command will use 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 users can run the command az login. For users running on a system with a default web browser the Azure cli will launch the browser to authenticate the user.

Azure CLI Account Sign In

For systems without a default web browser, the az login command will use 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

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 users can run the Connect-AzAccount cmdlet. By default, ike the Azure CLI, Connect-AzAccount will launch the default web browser to authenticate a user account.

Azure PowerShell Account Sign In

If interactive authentication cannot be supported in the session, then the -UseDeviceAuthentication argument will force 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 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 plugin package. This package provides the dependencies of VisualStudioCodeCredential and enables it. See Plugins.

It's a known issue that VisualStudioCodeCredential doesn't work with Azure Account extension 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.

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 in the Azure portal for your web application first.

Key concepts

If this is your first time using @azure/identity or the Microsoft Identity platform (Azure AD), read Using @azure/identity with Microsoft Identity Platform first. This document provides a deeper understanding of the platform and how to configure your Azure account correctly.

Credentials

A credential is a class which 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 Azure AD, and it offers a variety of credential classes capable of acquiring an Azure AD token to authenticate service requests. All of the credential classes in this library are implementations of the TokenCredential abstract class, and any of them can be used by to construct service clients capable of authenticating with a TokenCredential.

See Credential Classes.

DefaultAzureCredential

The DefaultAzureCredential is appropriate for most scenarios where the application is intended to ultimately be run in Azure. This is because the DefaultAzureCredential combines credentials commonly used to authenticate when deployed with credentials used to authenticate in a development environment.

Note: DefaultAzureCredential is intended to simplify getting started with the SDK by handling common scenarios with reasonable default behaviors. Developers who want more control or whose scenario isn't served by the default settings should use other credential types.

If used from Node.js, the DefaultAzureCredential will attempt to authenticate via the following mechanisms in order:

DefaultAzureCredential authentication flow

  1. Environment - The DefaultAzureCredential will read account information specified via environment variables and use it to authenticate.
  2. Workload Identity - If the application is deployed to Azure Kubernetes Service with Managed Identity enabled, DefaultAzureCredential will authenticate with it.
  3. Managed Identity - If the application is deployed to an Azure host with Managed Identity enabled, the DefaultAzureCredential will authenticate with that account.
  4. Azure Developer CLI - If the developer has authenticated an account via the Azure Developer CLI azd auth login command, the DefaultAzureCredential will authenticate with that account.
  5. Azure CLI - If the developer has authenticated an account via the Azure CLI az login command, the DefaultAzureCredential will authenticate with that account.
  6. Azure PowerShell - If the developer has authenticated using the Azure PowerShell module Connect-AzAccount command, the DefaultAzureCredential will authenticate with that account.
Continuation policy

As of version 3.3.0, DefaultAzureCredential will attempt 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 will continue to the next credential in the flow. Deployed service credentials will 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, 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-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 does not need to be repeated as long as a cached token is available.
  • @azure/identity-vscode, which provides the dependencies of VisualStudioCodeCredential and enables it. Without this plugin, the VisualStudioCodeCredential in this package will throw a CredentialUnavailableError. The plugin provides the underlying implementation of this credential, enabling it for use both on its own and as part of the DefaultAzureCredential described above.

Examples

You can find more examples of using various credentials in Azure Identity Examples Page

Authenticate with the DefaultAzureCredential

This example demonstrates authenticating the KeyClient from the @azure/keyvault-keys client library using the DefaultAzureCredential.

// The default credential first checks environment variables for configuration as described above.
// If environment configuration is incomplete, it will try managed identity.

// Azure Key Vault service to use
import { KeyClient } from "@azure/keyvault-keys";

// Azure authentication library to access Azure Key Vault
import { DefaultAzureCredential } from "@azure/identity";

// 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 the 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 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 the ChainedTokenCredential

While the 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 which will attempt to authenticate using two differently configured instances of ClientSecretCredential, to then authenticate the KeyClient from the @azure/keyvault-keys:

import { ClientSecretCredential, ChainedTokenCredential } from "@azure/identity";

// 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
import { KeyClient } from "@azure/keyvault-keys";
const client = new KeyClient(vaultUrl, credentialChain);

Managed identity support

The Managed identity authentication is supported via either the DefaultAzureCredential or the ManagedIdentityCredential credential classes directly for the following Azure services:

For examples of how to use managed identity for authentication, see the examples.

Cloud configuration

Credentials default to authenticating to the Azure AD 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 interface defines authorities for well-known clouds. For the US Government cloud, you could instantiate a credential this way:

import { AzureAuthorityHosts, ClientSecretCredential } from "@azure/identity";
const credential = new ClientSecretCredential(
  "<YOUR_TENANT_ID>",
  "<YOUR_CLIENT_ID>",
  "<YOUR_CLIENT_SECRET>",
  {
    authorityHost: AzureAuthorityHosts.AzureGovernment,
  }
);

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

Authenticate Azure-hosted applications

CredentialUsageExample
DefaultAzureCredentialProvides a simplified authentication experience to quickly start developing applications run in Azure.example
ChainedTokenCredentialAllows users to define custom authentication flows composing multiple credentials.example
EnvironmentCredentialAuthenticates a service principal or user via credential information specified in environment variables.example
ManagedIdentityCredentialAuthenticates the managed identity of an Azure resource.example
WorkloadIdentityCredentialSupports Azure AD workload identity on Kubernetes.

Authenticate service principals

CredentialUsageExampleReference
ClientAssertionCredentialAuthenticates a service principal using a signed client assertion.exampleService principal authentication
ClientCertificateCredentialAuthenticates a service principal using a certificate.exampleService principal authentication
ClientSecretCredentialAuthenticates a service principal using a secret.exampleService principal authentication

Authenticate users

CredentialUsageExampleReference
AuthorizationCodeCredentialAuthenticates a user with a previously obtained authorization code.exampleOAuth2 authentication code
DeviceCodeCredentialInteractively authenticates a user on devices with limited UI.exampleDevice code authentication
InteractiveBrowserCredentialInteractively authenticates a user with the default system browser. Read more about how this happens here.exampleOAuth2 authentication code
OnBehalfOfCredentialPropagates the delegated user identity and permissions through the request chainOn-behalf-of authentication
UsernamePasswordCredentialAuthenticates a user with a username and password.exampleUsername + password authentication

Authenticate via development tools

CredentialUsageExampleReference
AzureCliCredentialAuthenticate in a development environment with the Azure CLI.exampleAzure CLI authentication
AzureDeveloperCliCredentialAuthenticate in a development environment with the enabled user or service principal in Azure Developer CLI.Azure Developer CLI Reference
AzurePowerShellCredentialAuthenticate in a development environment using Azure PowerShell.exampleAzure PowerShell authentication
VisualStudioCodeCredentialAuthenticates as the user signed in to the Visual Studio Code Azure Account extension.VS Code Azure Account extension

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 nameValue
AZURE_CLIENT_IDID of an Azure AD application
AZURE_TENANT_IDID of the application's Azure AD tenant
AZURE_CLIENT_SECRETone of the application's client secrets
Service principal with certificate
Variable nameValue
AZURE_CLIENT_IDID of an Azure AD application
AZURE_TENANT_IDID of the application's Azure AD tenant
AZURE_CLIENT_CERTIFICATE_PATHpath to a PEM-encoded certificate file including private key
AZURE_CLIENT_CERTIFICATE_PASSWORDpassword of the certificate file, if any
Username and password
Variable nameValue
AZURE_CLIENT_IDID of an Azure AD application
AZURE_TENANT_IDID of the application's Azure AD tenant
AZURE_USERNAMEa username (usually an email address)
AZURE_PASSWORDthat user's password

Configuration is attempted in the above order. For example, if values for a client secret and certificate are both present, the client secret will be used.

Continuous Access Evaluation

As of version 3.3.0, accessing resources protected by Continuous Access Evaluation (CAE) is possible on a per-request basis. This can be enabled using the GetTokenOptions.enableCae(boolean) API. 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 Azure AD to obtain access tokens.

The Azure Identity library offers both in-memory and persistent disk caching. For more details, see the token caching documentation.

Troubleshooting

For assistance with troubleshooting, see the troubleshooting guide.

Next steps

Read the documentation

API documentation for this library can be found on our documentation site.

Client library support

Client and management libraries listed on the Azure SDK releases page that support Azure AD 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 service.

For other open issues, see the library's GitHub repository.

Provide feedback

If you encounter bugs or have suggestions, please open an issue.

Contributing

If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.

Impressions

msal-identity

Keywords

FAQs

Package last updated on 29 Sep 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc