Authenticate to Azure for development and runtime environments
To authenticate to Azure, create a service principal to use the Azure SDKs for JavaScript.
Authenticate to the Azure platform
Generally for most services and functionality, you need to authenticate with a Identity credential method to create a token. The token is passed to the SDK to authorize your use. There are several credential methods, some require more extensive setup but are built for production service use.
Find package-specific instructions to authenticate in each npm Azure SDK package's readme.md.
Interactive authentication for quickstarts and tutorials
To use a quickstart or tutorial for the Azure services, the quickest credential method is interactive login. With this method, you complete a few quick steps:
- You run the code.
- A message displays with an authentication URL and a token.
- Open a browser to that URL and enter the token. Depending on your Azure authentication requirements, a second authentication step may be required.
- When you have completed the authentication, you can close the browser.
- The code continues to run.
An example of interactive login authentication in a browser requires the configuration setting for the tenant and client ID for the Azure Active Directory application you are authenticating to. An example of this code is:
function withInteractiveBrowserCredential() {
const credential = new InteractiveBrowserCredential({
tenantId: "<YOUR_TENANT_ID>",
clientId: "<YOUR_CLIENT_ID>"
});
const client = new SecretClient("https://key-vault-name.vault.azure.net", credential);
}
Because this method requires an interactive login each time the code runs, you will want to replace this method with a non-interactive credential method once you are ready to begin your development work for the Azure platform.
Because this code doesn't use any authentication secrets, you can check this code to source control.
Azure authentication for development and production use
When you are ready to begin your development work, we recommend you select the following credentials:
| Local development | Deployed application |
|---|---|
| ClientSecretCredential. After you create your service principal and retrieve your client ID, tenant ID, and secret, this credential is quick to use and doesn't require environment variables. | When you plan to deploy to production, use the DefaultAzureCredential which requires environment variables. This credential method provides the benefit of not needing to store or use secrets in source control. |
There are other credential classes, which allow you to control authentication for specific purposes.
1. Create a service principal
Create a service principal and configure its access to Azure resources. The service principal is required to use the DefaultAzureCredential.
Create the service principal with the Azure az ad sp create-for-rbac command with the Azure CLI or Cloud Shell.
az ad sp create-for-rbac --name YOUR-SERVICE-PRINCIPAL-NAME --role Contributor --scopes /subscriptions/mySubscriptionIDThe response from the command includes secrets you need to store securely such as in Azure Key Vault:
{ "appId": "YOUR-SERVICE-PRINCIPAL-ID", "displayName": "YOUR-SERVICE-PRINCIPAL-NAME", "name": "http://YOUR-SERVICE-PRINCIPAL-NAME", "password": "!@#$%", "tenant": "YOUR-TENANT-ID" }
You can also create a service principal with:
2. Configure your environment variables
In the Azure cloud environments, you need to configure the following environment variables. Do not change the names because the Azure Identity SDK requires these exact environment names. These environment variables are REQUIRED for the context to use DefaultAzureCredential.
AZURE_TENANT_ID:tenantfrom the service principal output above.AZURE_CLIENT_ID:appIdfrom the service principal output above.AZURE_CLIENT_SECRET:passwordfrom the service principal output above.
3. List Azure subscriptions with service principal
Use the new service principal to authenticate with Azure and list your subscriptions.
Install the dependencies: Azure SDK for Identity, Azure Subscriptions SDK.
npm install @azure/identity @azure/arm-subscriptions --saveCreate a JavaScript file, named list.js, with the following code:
const { ClientSecretCredential, DefaultAzureCredential, } = require("@azure/identity"); const { SubscriptionClient } = require("@azure/arm-subscriptions"); require("dotenv").config(); let credentials = null; const tenantId = process.env["AZURE_TENANT_ID"]; const clientId = process.env["AZURE_CLIENT_ID"]; const secret = process.env["AZURE_CLIENT_SECRET"]; if (process.env.NODE_ENV && process.env.NODE_ENV === "production") { // production credentials = new DefaultAzureCredential(); } else { // development if (tenantId && clientId && secret) { console.log("development"); credentials = new ClientSecretCredential(tenantId, clientId, secret); } else { credentials = new DefaultAzureCredential(); } } async function listSubscriptions() { try { // use credential to authenticate with Azure SDKs const client = new SubscriptionClient(credentials); // get details of each subscription for await (const item of client.subscriptions.list()) { const subscriptionDetails = await client.subscriptions.get( item.subscriptionId ); /* Each item looks like: { id: '/subscriptions/123456', subscriptionId: '123456', displayName: 'YOUR-SUBSCRIPTION-NAME', state: 'Enabled', subscriptionPolicies: { locationPlacementId: 'Internal_2014-09-01', quotaId: 'Internal_2014-09-01', spendingLimit: 'Off' }, authorizationSource: 'RoleBased' }, */ console.log(subscriptionDetails); } } catch (error) { console.error(JSON.stringify(err)); } } listSubscriptions() .then(() => { console.log("done"); }) .catch((ex) => { console.log(ex); });If you aren't setting environment variables, replace the credential strings with your values.
const tenantId = process.env["AZURE_TENANT_ID"] || "REPLACE-WITH-YOUR-TENANT-ID"; const clientId = process.env["AZURE_CLIENT_ID"] || "REPLACE-WITH-YOUR-CLIENT-ID"; const secret = process.env["AZURE_CLIENT_SECRET"] || "REPLACE-WITH-YOUR-CLIENT-SECRET";Run the file to view the resource group list:
node list.jsView complete sample code and package.json:
Next steps
- View resource operation history
- Create web app with a secure domain name
- You can also create a service principal with:
Feedback
Issottometti u ara feedback għal