Why do I need a tenant when using #azure/keyvault-keys with #azure/identity, but not when using azure-keyvault? - node.js

I was using azure-keyvault but it's now deprecated. I'm using for encrypting and decrypting stuff. All I needed to operate was clientId, clientSecret and the key identifier.
Because now azure-keyvault is deprecated I switched to #azure/keyvault-keys/#azure/identity. For this I need a tenant (ClientSecretCredential) which I previously didn't need. Why is that or is there a way to not needing it?

When using a ClientSecretCredential, because a service principal belongs to a particular tenant, you have to specify that tenant rather than it coming back in a callback like the older code.
There are many different credential types, but our recommendation is to use DefaultAzureCredential which supports MSI, environment credentials (service principal using $AZURE_TENANT_ID, $AZURE_CLIENT_ID, and $AZURE_CLIENT_SECRET), and interactive browser login for most languages - soon with more credentials like azure CLI and Visual Studio. With support for azure CLI, that provides parity with the older packages like you used and then some. Just by using DefaultAzureCredential you get all that and it supports different environments by default, so you don't have to change your code to use different credentials for dev, staging, or production environments.
So like in the referenced example, you just instantiate a DefaultAzureCredenial and thats it. If you have your service principal environment variables defined, they will be used if Managed Identity (MSI) wasn't detected.
import { SecretClient } from '#azure/keyvault-secrets';
import { DefaultAzureCredential } from '#azure/identity';
import { CosmosClient } from '#azure/cosmos';
const keyVaultUrl = process.env('APP_KEY_VAULT_URI');
const credential = new DefaultAzureCredential();
let storageClient;
let cosmosClient;
async function configureClients() {
const kvClient = new SecretClient(keyVaultUrl, credential);
const storageUri = await client.getSecret('storageUri');
const cosmosDbConnectionString = await client.getSecret('cosmosDb');
cosmosClient = new CosmosClient(cosmosDbConnectonString);
storageClient = new BlobServiceClient(storageUri, credential);
The order of credentials is optimized for production workloads, but supports developer machines - pretty close to the order I listed them above.

Related

Access azure key vault from azure blob storage (static website)

I got a blob storage which I use as website.
This blob has a system assigned managed identity.
This identity is added to a key vault as access policy.
So actually it should be able to access the secrets.
But when I try it the way microsoft documented it I got an error.
const getSecret = async () => {
var credential = new DefaultAzureCredential({
ManagedIdentityClientId: "<blob-id>",
} as DefaultAzureCredentialOptions)
const keyVaultName = "<key-vault-name>"
const url = "https://" + keyVaultName + ".vault.azure.net"
const client = new SecretClient(url, credential)
const secret = await client.getSecret("function-key")
}
I got the error
Error: DefaultAzureCredential is not supported in the browser. Use InteractiveBrowserCredential instead.
at Module.60308 (defaultAzureCredential.browser.js:5:34)
Is this even possible?
Thanks!
Please check this azure-sdk-for-js issue according to which ,
interactive credentials is recommended instead of default
credentials.And for client side applications that run in the browser,
the InteractiveBrowserCredential is the only credential type that is
supported.Please check this github reference
So for interactive credentials for Node.js, if a clientId is
provided, the Azure AD app need to be configured to have a "Mobile and desktop applications" as redirect endpoint instead of web. See
set up redirect uri
See DefaultAzureCredential and examples
Also according to DefaultAzureCredential Class | Microsoft Docs
The following credential types if enabled will be tried, in order:
EnvironmentCredential >ManagedIdentityCredential >
SharedTokenCacheCredential > VisualStudioCredential >
VisualStudioCodeCredential > AzureCliCredential>
AzurePowerShellCredential >InteractiveBrowserCredential: uses browser to auth users - not enabled by default. Pass true to the DefaultAzureCredential to enable it.

Get Secret from Azure Keyvault using nodejs

I need to read the list of users in the Azure active directory. The client has created a Graph API application but they do not want to share the client secret of the application, instead they asked us to use the Key vault. How to access from the node.js application the key to retrieve the list of users?
I tried the below one but gave error and I am not sure how to authenticate.
const { DefaultAzureCredential } = require("#azure/identity");
const { SecretClient } = require("#azure/keyvault-secrets");
const credential = new DefaultAzureCredential();
const vaultName = "lsm-keyvault";
const url = `https://${vaultName}.vault.azure.net`;
const client = new SecretClient(url, credential);
const secretName = "Demo";
async function main() {
const result = await client.setSecret(secretName, "MySecretValue", {
enabled: false
});
console.log(result)
}
Well, if you run the code in local, the DefaultAzureCredential will use the environmental variables automatically.
So in your case, you need to register an application with Azure AD, and get the tenant id, client id(i.e. application id), client secret(i.e. application secret), set the environmental variables, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
For the 403 error you got, I notice you said It added as a compound entity, based on my experience, you did not add the correct service principal related to the AD App correctly to the Access policies of the keyvault. If you add it correctly, it will appear as APPLICATION, not COMPOUND IDENTITY.
So when you add it, you could search for the client Id(i.e. application Id) or the name of your App Registration directly, make sure you add the correct one. I gave the details in this similar issue, you could refer to it.
To retrieve the secret, the Get permission is enough, the code should be
const retrievedSecret = await client.getSecret(secretName);
I notice you use client.setSecret in your code, it is used to save a secret, to use it, you may need the Set permission.
For more details, see Quickstart: Azure Key Vault client library for Node.js (v4).
Update:
I have to eventually need to deploy this but not in azure but in another environment. How do I set the environment variables and access it.
If so, you need to change your code to authenticate, use the three values directly in the code.
Change the lines
const { DefaultAzureCredential } = require("#azure/identity");
const credential = new DefaultAzureCredential();
To
const { ClientSecretCredential } = require("#azure/identity");
const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
See - https://www.npmjs.com/package/#azure/identity/v/1.0.3#authenticating-as-a-service-principal
All you need to do is follow the below steps:
Create an App in the Azure Active Directory (Service Principal) from App Registrations.
Go to Key Vault resource, Access Policy blade, assign read access to this Azure AD App (Service Principal) that we created in the above step.
Set these 3 Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET in your App Service. Get the values of these variables from the app that we created in step 1.
Use DefaultAzureCredential that we are already using now. This will automatically pick the credentials from the environment variables that we defined in App Service for the authentication.
Another way is to obtain Key Vault token dynamically and use that token to get the secrets from the Key Vault - https://learn.microsoft.com/en-us/samples/azure-samples/app-service-msi-keyvault-node/app-service-msi-keyvault-node/
Helpful Reference:
https://www.rahulpnath.com/blog/defaultazurecredential_from_azure_sdk/

Azure SDK use CLI Creds or Managed Identity

When working with AWS, if you use aws configure to log in, you can use the AWS SDK without exposing credentials in any programming language from your local machine. If anything is running inside aws later (Lambda, EC2, whatever) the exact same code does use the resource assigned IAM Role without any configuration.
I try to get the same to work with Azure, I thought that the Azure.Identity.DefaultAzureCredential does do this. But I can't even run my code locally:
var blobServiceClient = new BlobServiceClient(storageUri, new DefaultAzureCredential());
var containerClient = await blobServiceClient.CreateBlobContainerAsync("test-container");
How can I get a BlobServiceClient that authenticates using the CLI creds on my local machine, and a managed identity if running inside an AppService.
In your scenario, as you used, the DefaultAzureCredential is the best choice along with the BlobServiceClient, but it does not use CLI credentials to authenticate.
To make it work, just set the Environment variables with AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET of your service principal. In Azure, it uses the MSI to authenticate.
If you want to use CLI credentials to authenticate, there is AzureServiceTokenProvider, it can also access azure storage, but you could not use it along with BlobServiceClient, you need to get the access token with the resource https://storage.azure.com,
var azureServiceTokenProvider2 = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider2.GetAccessTokenAsync("https://storage.azure.com").ConfigureAwait(false);
then use the access token to call Storge REST API, I think the first option is more convenient, to use which one, it is up to you.

Unable to connect to Azure Key Vault from Azure Web App

I am trying to access Azure Key Vault from my Azure App Service. I followed the steps outlined on this documentation: https://learn.microsoft.com/en-us/azure/key-vault/managed-identity (turned on system assigned identity for the app service, updated the access policy of the key vault to include the app with Get,List secret permissions).
However, when I run the web application, it is not able to get the secret from the key vault and my web service hits the following error:
502 - Web server received an invalid response while acting as a gateway or proxy server.
There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.
This is what my code looks like:
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var secret = keyVaultClient.GetSecretAsync(KeyVaultUrl);
authenticationKey = secret.Result.Value;
The service gets stuck on the secret.Result.Value line. Is there something else I need to do?
This is much easier with the new package, like Azure.Security.KeyVault.Secrets. Together with Azure.Identity, you can just pass a DefaultAzureCredential like in our samples.
var client = new SecretClient(
new Uri("https://myvault.vault.azure.net"),
new DefaultAzureCredential());
KeyVaultSecret secret = await client.GetSecretAsync("secret-name");
string authenticationKey = secret.Value;
The DefaultAzureCredential is optimized to work for managed identity, service principals from the environment, and interactive logins to support the same code running both in production and on developer machines. The new libraries are also faster with fewer allocations, and have much better diagnostics - defaulted to on when using Azure Application Monitor.
They target netstandard2.0 so should be compatible with the older packages these replace. Would you be able to upgrade? We're only making critical fixes for the older packages, and recommending people upgrade to Azure.* packages intead of the older Microosft.Azure.* packages.
As for the problem itself, it's hard to say without knowing when you're calling this in your application. During startup? What version of .NET? What are you using for your ASP.NET application framework?
While it's probably not the cause of the problem, it's hard to ignore that you're calling an async method synchronously, which can also cause problems. If you're in an async method, you should write your code like so:
var secret = await keyVaultClient.GetSecretAsync(KeyVaultUrl);
authenticationKey = secret.Value;
If not, call:
var secret = keyVaultClient.GetSecretAsnc(KeyVaultUrl).GetAwaiter().GetResult();
This is not recommended, though. In the new packages I mentioned above, we have both sync and async versions that are either sync or async all the way through the call stack and safer to use. Generally, though, you should use async calls - especially for network traffic like accessing Key Vault because, depending on what thread you call it, it can hang your UI.
When you test in local:
Add your vs signed account into azure keyvault. Go to keyvault> Access policy> add your account with get secret permmission.
When you publish to azure:
1.Enable webapp MSI.
2.Go to keyvault> Access policy> add your webapp's service principal with get secret permission.
The code:
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new Microsoft.Azure.KeyVault.KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var secret = keyVaultClient.GetSecretAsync("https://yourkevaultname.vault.azure.net/secrets/secretname/437d301daxxxxxx");
var authenticationKey = secret.Result.Value;
ViewBag.Message = authenticationKey.ToString();

Authenticate Azure Management SDK in .NET Core?

I'm running ASP.NET Core application (.Net Core 3.0) and have referenced nuGet package Microsoft.Azure.Management.WebSites. It seems like there are half a dozen ways to connect to Azure and I'm hoping that is the correct one for my environment.
I'm attempting to instantiate a WebSiteManagementClient so that I can modify some AppService settings (scale service plan up/down). To that end, I need an instance of ServiceClientCredentials. I can't seem to find a way to get the proper credentials together.
I've followed several different articles, all of them advocate a different method.
What's the easiest way to get authenticated against the Azure Management SDK?
Ideally, avoiding Azure Active Directory. I've attempted multiple times trying to set up an App Registration with the appropriate permissions, and I can't seem to get it together.
The app connecting and making the change will be an ASP.NET website running in Azure itself, if it makes a difference.
Thanks in advance!
Code so far:
using Microsoft.Azure.Management.WebSites;
var credentials = await GetCredentials(); // <-- ???
WebSiteManagementClient client = new WebSiteManagementClient(credentials);
client.SubscriptionId = "xxx-xxx-xxxx-xxxx";
Try this :
static void Main(string[] args)
{
string tenantId = "<your tenant ID>";
string clientId = "<your azure ad app ID>";
string clientSecret = "<azure ad app secret>";
string subscriptionId = "<your subscription ID>";
WebSiteManagementClient client = new WebSiteManagementClient(GetCredsFromServicePrincipal(tenantId, clientId, clientSecret));
client.SubscriptionId = subscriptionId;
foreach (var ap in client.app.List()) {
Console.WriteLine(ap.Id);
}
}
private static TokenCredentials GetCredsFromServicePrincipal(String tenantId,String clientId, String clientSecret)
{
var authority = #"https://login.microsoftonline.com/" + tenantId;
var authContext = new AuthenticationContext(authority);
var credential = new ClientCredential(clientId, clientSecret);
var authResult = authContext.AcquireTokenAsync("https://management.azure.com", credential).GetAwaiter().GetResult();
return new TokenCredentials(authResult.AccessToken);
}
Result (list all website ids):
As this sample use ServicePrincipal to access your azure website resources, so you should grant associated permissions it in your subscription "Access control (IAM)" balde, such as assigning "website contributor" and "web plan contributor" to it so it has permission to manage your website resources . Hope it helps.
The new Azure.Identity library seems to be the recommended way for authenticating services within Azure. In particular the DefaultAzureCredentials() class works seamlessly in local development scenarios and in deployed code without having to make any code changes.
This is easy to use with the newer management SDKs (the ones with names like Azure.ResourceManager...) because we can just write new DefaultAzureCredentials() and pass that to the management SDK when creating a new client.
Unfortunately, the older management SDKs (the ones with names like Microsoft.Azure.Management...) do not integrate with Azure.Identity "out-of-the-box". They also do not plan to add support for Azure.Identity to these older APIs because they are instead focusing on porting everything to the newer versions.
However, not every resource in Azure has a new version management API yet and so in some cases you're stuck using the old ones. Fortunately, there is a relatively straight forward way to bridge the gap and still use Azure.Identity with those older APIs.
There's a GitHub repo which contains an example of how to achieve this. I think it's by one of the developers on the Microsoft team, but isn't officially supported by Microsoft. There is no NuGet package for it and they recommend just copying the bits you need.
I actually found that the code in that sample repo was overly complex for my needs and in my case that all I needed was this. Note, I've copied this from my F# project without testing it, so I might have made a mistake in the conversion to C#, but hopefully it's close enough that you get the idea.
class AzureIdentityFluentCredentialAdapter : AzureCredentials
{
public AzureIdentityFluentCredentialAdapter(string tenantId)
: base(default(DeviceCredentialInformation), tenantId, AzureEnvironment.AzureGlobalCloud)
{
}
public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var creds = DefaultAzureCredential() // Use the new Azure.Identity library to get access tokens
var accessToken = await creds.GetTokenAsync(
new TokenRequestContent(new [] { "https://management.azure.com/.default" }),
cancellationToken);
return await TokenCredentials(accessToken.Token)
.ProcessHttpRequestAsync(request, cancellationToken);
}
}
This example doesn't do any token caching, but for my purposes I wasn't too bothered about this. It's also hardcoded the scope that I request the token for because I knew I was only going to be using this with the Azure management API.

Resources