The azure auth method allows authentication against Vault using
Azure Active Directory credentials. It treats Azure as a Trusted Third Party
and expects a JSON Web Token (JWT)
signed by Azure Active Directory for the configured tenant.
This method supports authentication for system-assigned and user-assigned
managed identities. See Azure Managed Service Identity (MSI) for more information about these resources.
System-assigned identities are unique to every virtual machine in Azure. If the
virtual machines using Azure auth are recreated frequently, using system-assigned
identities could result in a lot of Vault entities. For environments with high ephemeral
workloads, user-assigned identities are recommended.
The role and jwt parameters are required. When using bound_service_principal_ids and bound_group_ids in the token roles, all the information is required in the JWT (except for vm_name and vmss_name). When using other bound_* parameters, calls to Azure APIs will be made and subscription id, resource group name, and vm name/vmss_name are all required and can be obtained through instance metadata.
Auth methods must be configured in advance before machines can authenticate.
These steps are usually completed by an operator or configuration management
tool.
Roles are associated with an authentication type/entity and a set of Vault
policies. Roles are configured with constraints specific to the
authentication type, as well as overall constraints and configuration for
the generated auth tokens.
For the complete list of role options, please see the API documentation.
The following section is only relevant if you decide to enable the azure auth
method as an external plugin. The azure plugin method is integrated into Vault as
a builtin method by default.
Assuming you have saved the binary vault-plugin-auth-azure to some folder and
configured the plugin directory
for your server at path/to/plugins:
The following example demonstrates the Azure auth method to authenticate
with Vault.
Go
Go
C#
package main
import("context""fmt"
vault "github.com/hashicorp/vault/api"
auth "github.com/hashicorp/vault/api-docs/auth/azure")// Fetches a key-value secret (kv-v2) after authenticating to Vault via Azure authentication.// This example assumes you have a configured Azure AD Application.funcgetSecretWithAzureAuth()(string,error){
config := vault.DefaultConfig()// modify for more granular configuration
client, err := vault.NewClient(config)if err !=nil{return"", fmt.Errorf("unable to initialize Vault client: %w", err)}
azureAuth, err := auth.NewAzureAuth("dev-role-azure",)if err !=nil{return"", fmt.Errorf("unable to initialize Azure auth method: %w", err)}
authInfo, err := client.Auth().Login(context.TODO(), azureAuth)if err !=nil{return"", fmt.Errorf("unable to login to Azure auth method: %w", err)}if authInfo ==nil{return"", fmt.Errorf("no auth info was returned after login")}// get secret
secret, err := client.Logical().Read("kv-v2/data/creds")if err !=nil{return"", fmt.Errorf("unable to read secret: %w", err)}
data, ok := secret.Data["data"].(map[string]interface{})if!ok {return"", fmt.Errorf("data type assertion failed: %T %#v", secret.Data["data"], secret.Data["data"])}// data map can contain more than one key-value pair,// in this case we're just grabbing one of them
key :="password"
value, ok := data[key].(string)if!ok {return"", fmt.Errorf("value type assertion failed: %T %#v", data[key], data[key])}return value,nil}
package main
import("context""fmt" vault "github.com/hashicorp/vault/api" auth "github.com/hashicorp/vault/api-docs/auth/azure")// Fetches a key-value secret (kv-v2) after authenticating to Vault via Azure authentication.// This example assumes you have a configured Azure AD Application.funcgetSecretWithAzureAuth()(string,error){ config := vault.DefaultConfig()// modify for more granular configuration client, err := vault.NewClient(config)if err !=nil{return"", fmt.Errorf("unable to initialize Vault client: %w", err)} azureAuth, err := auth.NewAzureAuth("dev-role-azure",)if err !=nil{return"", fmt.Errorf("unable to initialize Azure auth method: %w", err)} authInfo, err := client.Auth().Login(context.TODO(), azureAuth)if err !=nil{return"", fmt.Errorf("unable to login to Azure auth method: %w", err)}if authInfo ==nil{return"", fmt.Errorf("no auth info was returned after login")}// get secret secret, err := client.Logical().Read("kv-v2/data/creds")if err !=nil{return"", fmt.Errorf("unable to read secret: %w", err)} data, ok := secret.Data["data"].(map[string]interface{})if!ok {return"", fmt.Errorf("data type assertion failed: %T %#v", secret.Data["data"], secret.Data["data"])}// data map can contain more than one key-value pair,// in this case we're just grabbing one of them key :="password" value, ok := data[key].(string)if!ok {return"", fmt.Errorf("value type assertion failed: %T %#v", data[key], data[key])}return value,nil}
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Net;usingSystem.Net.Http;usingSystem.Text;usingNewtonsoft.Json;usingVaultSharp;usingVaultSharp.V1.AuthMethods;usingVaultSharp.V1.AuthMethods.Azure;usingVaultSharp.V1.Commons;namespaceExamples{publicclassAzureAuthExample{publicclassInstanceMetadata{publicstring name {get;set;}publicstring resourceGroupName {get;set;}publicstring subscriptionId {get;set;}}conststring MetadataEndPoint ="http://169.254.169.254/metadata/instance?api-version=2017-08-01";conststring AccessTokenEndPoint ="http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/";/// <summary>/// Fetches a key-value secret (kv-v2) after authenticating to Vault via Azure authentication./// This example assumes you have a configured Azure AD Application./// </summary>publicstringGetSecretWithAzureAuth(){string vaultAddr = Environment.GetEnvironmentVariable("VAULT_ADDR");if(String.IsNullOrEmpty(vaultAddr)){thrownewSystem.ArgumentNullException("Vault Address");}string roleName = Environment.GetEnvironmentVariable("VAULT_ROLE");if(String.IsNullOrEmpty(roleName)){thrownewSystem.ArgumentNullException("Vault Role Name");}string jwt =GetJWT();InstanceMetadata metadata =GetMetadata();IAuthMethodInfo authMethod =newAzureAuthMethodInfo(roleName: roleName,jwt: jwt,subscriptionId: metadata.subscriptionId,resourceGroupName: metadata.resourceGroupName,virtualMachineName: metadata.name);var vaultClientSettings =newVaultClientSettings(vaultAddr, authMethod);IVaultClient vaultClient =newVaultClient(vaultClientSettings);// We can retrieve the secret from the VaultClient objectSecret<SecretData> kv2Secret =null;
kv2Secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(path:"/creds").Result;var password = kv2Secret.Data.Data["password"];return password.ToString();}/// <summary>/// Query Azure Resource Manage for metadata about the Azure instance/// </summary>privateInstanceMetadataGetMetadata(){HttpWebRequest metadataRequest =(HttpWebRequest)WebRequest.Create(MetadataEndPoint);
metadataRequest.Headers["Metadata"]="true";
metadataRequest.Method ="GET";HttpWebResponse metadataResponse =(HttpWebResponse)metadataRequest.GetResponse();StreamReader streamResponse =newStreamReader(metadataResponse.GetResponseStream());string stringResponse = streamResponse.ReadToEnd();var resultsDict = JsonConvert.DeserializeObject<Dictionary<string, InstanceMetadata>>(stringResponse);return resultsDict["compute"];}/// <summary>/// Query Azure Resource Manager (ARM) for an access token/// </summary>privatestringGetJWT(){HttpWebRequest request =(HttpWebRequest)WebRequest.Create(AccessTokenEndPoint);
request.Headers["Metadata"]="true";
request.Method ="GET";HttpWebResponse response =(HttpWebResponse)request.GetResponse();// Pipe response Stream to a StreamReader and extract access tokenStreamReader streamResponse =newStreamReader(response.GetResponseStream());string stringResponse = streamResponse.ReadToEnd();var resultsDict = JsonConvert.DeserializeObject<Dictionary<string,string>>(stringResponse);return resultsDict["access_token"];}}}
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Net;usingSystem.Net.Http;usingSystem.Text;usingNewtonsoft.Json;usingVaultSharp;usingVaultSharp.V1.AuthMethods;usingVaultSharp.V1.AuthMethods.Azure;usingVaultSharp.V1.Commons;namespaceExamples{publicclassAzureAuthExample{publicclassInstanceMetadata{publicstring name {get;set;}publicstring resourceGroupName {get;set;}publicstring subscriptionId {get;set;}}conststring MetadataEndPoint ="http://169.254.169.254/metadata/instance?api-version=2017-08-01";conststring AccessTokenEndPoint ="http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/";/// <summary>/// Fetches a key-value secret (kv-v2) after authenticating to Vault via Azure authentication./// This example assumes you have a configured Azure AD Application./// </summary>publicstringGetSecretWithAzureAuth(){string vaultAddr = Environment.GetEnvironmentVariable("VAULT_ADDR");if(String.IsNullOrEmpty(vaultAddr)){thrownewSystem.ArgumentNullException("Vault Address");}string roleName = Environment.GetEnvironmentVariable("VAULT_ROLE");if(String.IsNullOrEmpty(roleName)){thrownewSystem.ArgumentNullException("Vault Role Name");}string jwt =GetJWT();InstanceMetadata metadata =GetMetadata();IAuthMethodInfo authMethod =newAzureAuthMethodInfo(roleName: roleName,jwt: jwt,subscriptionId: metadata.subscriptionId,resourceGroupName: metadata.resourceGroupName,virtualMachineName: metadata.name);var vaultClientSettings =newVaultClientSettings(vaultAddr, authMethod);IVaultClient vaultClient =newVaultClient(vaultClientSettings);// We can retrieve the secret from the VaultClient objectSecret<SecretData> kv2Secret =null; kv2Secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(path:"/creds").Result;var password = kv2Secret.Data.Data["password"];return password.ToString();}/// <summary>/// Query Azure Resource Manage for metadata about the Azure instance/// </summary>privateInstanceMetadataGetMetadata(){HttpWebRequest metadataRequest =(HttpWebRequest)WebRequest.Create(MetadataEndPoint); metadataRequest.Headers["Metadata"]="true"; metadataRequest.Method ="GET";HttpWebResponse metadataResponse =(HttpWebResponse)metadataRequest.GetResponse();StreamReader streamResponse =newStreamReader(metadataResponse.GetResponseStream());string stringResponse = streamResponse.ReadToEnd();var resultsDict = JsonConvert.DeserializeObject<Dictionary<string, InstanceMetadata>>(stringResponse);return resultsDict["compute"];}/// <summary>/// Query Azure Resource Manager (ARM) for an access token/// </summary>privatestringGetJWT(){HttpWebRequest request =(HttpWebRequest)WebRequest.Create(AccessTokenEndPoint); request.Headers["Metadata"]="true"; request.Method ="GET";HttpWebResponse response =(HttpWebResponse)request.GetResponse();// Pipe response Stream to a StreamReader and extract access tokenStreamReader streamResponse =newStreamReader(response.GetResponseStream());string stringResponse = streamResponse.ReadToEnd();var resultsDict = JsonConvert.DeserializeObject<Dictionary<string,string>>(stringResponse);return resultsDict["access_token"];}}}