New Vault OSS Now Includes Multi-factor Authentication! Learn more
  • Overview
    • Automated PKI Infrastructure
    • Data Encryption & Tokenization
    • Database Credential Rotation
    • Dynamic Secrets
    • Identity-based Access
    • Key Management
    • Kubernetes Secrets
    • Secrets Management
  • Enterprise
  • Tutorials
  • Docs
  • API
  • Community
GitHubTry Cloud
Download
    • v1.10.x (latest)
    • v1.9.x
    • v1.8.x
    • v1.7.x
    • v1.6.x
    • v1.5.x
    • v1.4.x
  • What is Vault?
  • Use Cases
    • CLI Quick Start
    • HCP Quick Start
    • Developer Quick Start

  • Browser Support
  • Installing Vault
    • Overview
    • Architecture
    • High Availability
    • Integrated Storage
    • Security Model
    • Telemetry
    • Token Authentication
    • Key Rotation
    • Replication
    • Limits and Maximums
    • Overview
    • 'Dev' Server
    • Seal/Unseal
    • Namespace API Lock
    • Lease, Renew, and Revoke
    • Authentication
    • Tokens
    • Identity
    • OIDC Provider
    • Response Wrapping
    • Policies
    • Password Policies
    • Username Templating
    • High Availability
    • Storage
      • Overview
      • Autopilot
    • PGP, GnuPG, and Keybase
    • Recovery Mode
    • Resource Quotas
      • Overview
      • FAQ
    • Transform
    • Mount Migration
    • Overview
      • Overview
      • TCP
    • replication
      • Overview
      • AliCloud KMS
      • AWS KMS
      • Azure Key Vault
      • GCP Cloud KMS
      • OCI KMS
      • HSM PKCS11 ENT
      • Vault Transit
    • sentinel
      • Overview
      • Consul
      • Kubernetes
      • Overview
      • Aerospike
      • Alicloud OSS
      • Azure
      • Cassandra
      • CockroachDB
      • Consul
      • CouchDB
      • DynamoDB
      • Etcd
      • Filesystem
      • FoundationDB
      • Google Cloud Spanner
      • Google Cloud Storage
      • In-Memory
      • Manta
      • MSSQL
      • MySQL
      • OCI Object Storage
      • PostgreSQL
      • Integrated Storage (Raft)
      • S3
      • Swift
      • Zookeeper
    • telemetry
    • ui
    • Log Completed Requests
    • Entropy Augmentation ENT
    • kms_library ENT
    • Overview
    • agent
      • Overview
      • disable
      • enable
      • list
      • Overview
      • disable
      • enable
      • help
      • list
      • move
      • tune
    • debug
    • delete
      • Overview
      • delete
      • destroy
      • enable-versioning
      • get
      • list
      • metadata
      • patch
      • put
      • rollback
      • undelete
      • Overview
      • lookup
      • renew
      • revoke
      • Overview
      • get
      • inspect
    • list
    • login
    • monitor
    • namespace
      • Overview
      • diagnose
      • generate-root
      • init
      • key-status
      • members
      • migrate
      • raft
      • rekey
      • rotate
      • seal
      • step-down
      • unseal
      • usage
    • path-help
      • Overview
      • deregister
      • info
      • list
      • register
      • reload
      • Overview
      • delete
      • fmt
      • list
      • read
      • write
    • read
      • Overview
      • disable
      • enable
      • list
      • move
      • tune
    • server
    • ssh
    • status
      • Overview
      • capabilities
      • create
      • lookup
      • renew
      • revoke
    • unwrap
    • version
    • version-history
    • write
    • Token Helpers
    • Overview
      • Overview
        • Overview
        • AliCloud
        • AppRole
        • AWS
        • Azure
        • Cert
        • CF
        • GCP
        • JWT
        • Kerberos
        • Kubernetes
        • Overview
        • File
      • Overview
        • Overview
        • Kubernetes
    • Templates
    • Windows service

    • Overview
    • Active Directory
    • AliCloud
    • AWS
    • Azure
    • Consul
    • Cubbyhole
      • Overview
      • Cassandra
      • Couchbase
      • Elasticsearch
      • HanaDB
      • IBM Db2
      • InfluxDB
      • MongoDB
      • MongoDB Atlas
      • MSSQL
      • MySQL/MariaDB
      • Oracle
      • PostgreSQL
      • Redshift
      • Snowflake
      • Custom
    • Google Cloud
    • Google Cloud KMS
      • Overview
      • Azure Key Vault
      • AWS KMS
      • GCP Cloud KMS
    • KMIP ENTERPRISE
      • Overview
      • K/V Version 1
      • K/V Version 2
      • Overview
      • Identity Tokens
      • OIDC Identity Provider
    • MongoDB Atlas
    • Nomad
    • OpenLDAP
    • PKI (Certificates)
    • RabbitMQ
      • Overview
      • Signed Certificates
      • SSH OTP
      • Dynamic Key
    • Terraform Cloud
    • TOTP
      • Overview
      • FF3-1 Tweak Usage
      • Tokenization Transform ENTERPRISE
    • Transit
    • Venafi (Certificates)
    • Overview
    • AppRole
    • AliCloud
    • AWS
    • Azure
    • Cloud Foundry
    • GitHub
    • Google Cloud
      • Overview
      • OIDC Providers
    • Kerberos
    • Kubernetes
    • LDAP
      • Overview
      • FAQ
    • Oracle Cloud Infrastructure
    • Okta
    • RADIUS
    • TLS Certificates
    • Tokens
    • Username & Password

    • App ID DEPRECATED
    • MFA LEGACY / UNSUPPORTED
    • Overview
    • File
    • Syslog
    • Socket
    • Overview
    • Plugin Architecture
    • Plugin Development
    • Plugin Management
    • Plugin Portal
  • Vault Integration Program
  • Troubleshoot

    • Overview
      • Overview
      • Agent Injector vs. Vault CSI Provider
        • Overview
        • Running Vault
        • Enterprise Licensing
        • Running Vault on OpenShift
        • Configuration
          • Overview
          • Development
          • Standalone with Load Balanced UI
          • Standalone with TLS
          • Standalone with Audit Storage
          • External Vault
          • Using Kubernetes Auth Method
          • HA Cluster with Consul
          • HA Cluster with Raft
          • HA Enterprise Cluster with Raft
          • HA Enterprise DR Clusters with Raft
          • HA Enterprise Performance Clusters with Raft
          • Vault Agent Injector TLS Configuration
          • Vault Agent Injector TLS with Cert-Manager
        • Overview
        • Annotations
        • Installation
        • Examples
        • Overview
        • Installation
        • Configurations
        • Examples
      • Overview
      • Vault Lambda Extension
      • Running Vault
      • Overview
      • Installation
      • Configuration
      • Troubleshooting
      • Overview
      • Installation
      • Troubleshooting

    • Overview
    • Upgrade Plugins
    • Upgrade to 1.10.x
    • Upgrade to 1.9.x
    • Upgrade to 1.8.x
    • Upgrade to 1.7.x
    • Upgrade to 1.6.3
    • Upgrade to 1.6.2
    • Upgrade to 1.6.1
    • Upgrade to 1.6.0
    • Upgrade to 1.5.3
    • Upgrade to 1.5.2
    • Upgrade to 1.5.1
    • Upgrade to 1.5.0
    • Upgrade to 1.4.6
    • Upgrade to 1.4.5
    • Upgrade to 1.4.4
    • Upgrade to 1.4.1
    • Upgrade to 1.4.0
    • Upgrade to 1.3.10
    • Upgrade to 1.3.9
    • Upgrade to 1.3.8
    • Upgrade to 1.3.5
    • Upgrade to 1.3.4
    • Upgrade to 1.3.3
    • Upgrade to 1.3.2
    • Upgrade to 1.3.0
    • Upgrade to 1.2.7
    • Upgrade to 1.2.6
    • Upgrade to 1.2.5
    • Upgrade to 1.2.4
    • Upgrade to 1.2.1
    • Upgrade to 1.2.0
    • Upgrade to 1.1.2
    • Upgrade to 1.1.1
    • Upgrade to 1.1.0
    • Upgrade to 1.0.0
    • Upgrade to 0.11.6
    • Upgrade to 0.11.2
    • Upgrade to 0.11.0
    • Upgrade to 0.10.4
    • Upgrade to 0.10.2
    • Upgrade to 0.10.0
    • Upgrade to 0.9.6
    • Upgrade to 0.9.3
    • Upgrade to 0.9.2
    • Upgrade to 0.9.1
    • Upgrade to 0.9.0
    • Upgrade to 0.8.0
    • Upgrade to 0.7.0
    • Upgrade to 0.6.4
    • Upgrade to 0.6.3
    • Upgrade to 0.6.2
    • Upgrade to 0.6.1
    • Upgrade to 0.6.0
    • Upgrade to 0.5.1
    • Upgrade to 0.5.0

    • Overview
    • 1.10.0
    • 1.9.0
    • 1.8.0
    • 1.7.0
    • 1.6.0
    • 1.5.0

    • Overview
    • FAQ

    • Overview
    • Feature Deprecation Notice and Plans
    • License
    • Client Count
    • Login MFA
    • Server Side Consistent Token

  • Glossary

    • Overview
      • Overview
      • Autoloading
      • FAQ
    • Replication
      • Overview
      • Behavioral Changes
      • Security
    • Automated Integrated Storage Snapshots
    • Lease Count Quotas
    • Entropy Augmentation
      • Overview
      • FIPS 140-2 Inside Vault
      • Seal Wrap for FIPS 140-2
    • Seal Wrap
    • Namespaces
    • Performance Standbys
    • Eventual Consistency
    • Control Groups
    • Managed Keys
      • Overview
      • Duo MFA
      • Okta MFA
      • PingID MFA
      • TOTP MFA
      • Overview
      • Examples
      • Properties
    • HCP Vault
Type '/' to Search

»Azure Auth Method

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.

»Prerequisites:

The following documentation assumes that the method has been mounted at auth/azure.

  • A configured Azure AD application which is used as the resource for generating MSI access tokens.
  • Client credentials (shared secret) for accessing the Azure Resource Manager with read access to compute endpoints. See Azure AD Service to Service Client Credentials

Required Azure API permissions to be granted to Vault user:

  • Microsoft.Compute/virtualMachines/*/read
  • Microsoft.Compute/virtualMachineScaleSets/*/read

NOTE: The above permissions are only required when the associated vm* parameters are used on login. Please see the API doc for more details.

If Vault is hosted on Azure, Vault can use MSI to access Azure instead of a shared secret. MSI must be enabled on the VMs hosting Vault.

The next sections review how the authN/Z workflows work. If you have already reviewed these sections, here are some quick links to:

  • Usage
  • API documentation docs.

»Authentication

»Via the CLI

The default path is /auth/azure. If this auth method was enabled at a different path, specify auth/my-path/login instead.

$ vault write auth/azure/login \
    role="dev-role" \
    jwt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
    subscription_id="12345-..." \
    resource_group_name="test-group" \
    vm_name="test-vm"
$ vault write auth/azure/login \
    role="dev-role" \
    jwt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
    subscription_id="12345-..." \
    resource_group_name="test-group" \
    vm_name="test-vm"

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.

For example:

$ vault write auth/azure/login role="dev-role" \
     jwt="$(curl -s 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F' -H Metadata:true | jq -r '.access_token')" \
     subscription_id=$(curl -s -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-08-01" | jq -r '.compute | .subscriptionId')  \
     resource_group_name=$(curl -s -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-08-01" | jq -r '.compute | .resourceGroupName') \
     vm_name=$(curl -s -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-08-01" | jq -r '.compute | .name')
$ vault write auth/azure/login role="dev-role" \
     jwt="$(curl -s 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F' -H Metadata:true | jq -r '.access_token')" \
     subscription_id=$(curl -s -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-08-01" | jq -r '.compute | .subscriptionId')  \
     resource_group_name=$(curl -s -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-08-01" | jq -r '.compute | .resourceGroupName') \
     vm_name=$(curl -s -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-08-01" | jq -r '.compute | .name')

»Via the API

The default endpoint is auth/azure/login. If this auth method was enabled at a different path, use that value instead of azure.

$ curl \
    --request POST \
    --data '{"role": "dev-role", "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}' \
    https://127.0.0.1:8200/v1/auth/azure/login
$ curl \
    --request POST \
    --data '{"role": "dev-role", "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}' \
    https://127.0.0.1:8200/v1/auth/azure/login

The response will contain the token at auth.client_token:

{
  "auth": {
    "client_token": "f33f8c72-924e-11f8-cb43-ac59d697597c",
    "accessor": "0e9e354a-520f-df04-6867-ee81cae3d42d",
    "policies": ["default", "dev", "prod"],
    "lease_duration": 2764800,
    "renewable": true
  }
}
{
  "auth": {
    "client_token": "f33f8c72-924e-11f8-cb43-ac59d697597c",
    "accessor": "0e9e354a-520f-df04-6867-ee81cae3d42d",
    "policies": ["default", "dev", "prod"],
    "lease_duration": 2764800,
    "renewable": true
  }
}

»Configuration

Auth methods must be configured in advance before machines can authenticate. These steps are usually completed by an operator or configuration management tool.

»Via the CLI

  1. Enable Azure authentication in Vault:

    $ vault auth enable azure
    
    $ vault auth enable azure
    
  2. Configure the Azure auth method:

    $ vault write auth/azure/config \
        tenant_id=7cd1f227-ca67-4fc6-a1a4-9888ea7f388c \
        resource=https://management.azure.com/ \
        client_id=dd794de4-4c6c-40b3-a930-d84cd32e9699 \
        client_secret=IT3B2XfZvWnfB98s1cie8EMe7zWg483Xy8zY004=
    
    $ vault write auth/azure/config \
        tenant_id=7cd1f227-ca67-4fc6-a1a4-9888ea7f388c \
        resource=https://management.azure.com/ \
        client_id=dd794de4-4c6c-40b3-a930-d84cd32e9699 \
        client_secret=IT3B2XfZvWnfB98s1cie8EMe7zWg483Xy8zY004=
    

    For the complete list of configuration options, please see the API documentation.

  3. Create a role:

    $ vault write auth/azure/role/dev-role \
        policies="prod,dev" \
        bound_subscription_ids=6a1d5988-5917-4221-b224-904cd7e24a25 \
        bound_resource_groups=vault
    
    $ vault write auth/azure/role/dev-role \
        policies="prod,dev" \
        bound_subscription_ids=6a1d5988-5917-4221-b224-904cd7e24a25 \
        bound_resource_groups=vault
    

    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.

»Via the API

  1. Enable Azure authentication in Vault:

    $ curl \
        --header "X-Vault-Token: ..." \
        --request POST \
        --data '{"type": "azure"}' \
        https://127.0.0.1:8200/v1/sys/auth/azure
    
    $ curl \
        --header "X-Vault-Token: ..." \
        --request POST \
        --data '{"type": "azure"}' \
        https://127.0.0.1:8200/v1/sys/auth/azure
    
  2. Configure the Azure auth method:

    $ curl \
        --header "X-Vault-Token: ..." \
        --request POST \
        --data '{"tenant_id": "...", "resource": "..."}' \
        https://127.0.0.1:8200/v1/auth/azure/config
    
    $ curl \
        --header "X-Vault-Token: ..." \
        --request POST \
        --data '{"tenant_id": "...", "resource": "..."}' \
        https://127.0.0.1:8200/v1/auth/azure/config
    
  3. Create a role:

    $ curl \
        --header "X-Vault-Token: ..." \
        --request POST \
        --data '{"policies": ["dev", "prod"], ...}' \
        https://127.0.0.1:8200/v1/auth/azure/role/dev-role
    
    $ curl \
        --header "X-Vault-Token: ..." \
        --request POST \
        --data '{"policies": ["dev", "prod"], ...}' \
        https://127.0.0.1:8200/v1/auth/azure/role/dev-role
    

»Plugin Setup

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:

  1. Enable the plugin in the catalog:

    $ vault write sys/plugins/catalog/auth/azure-auth \
        command="vault-plugin-auth-azure" \
        sha256="..."
    
    $ vault write sys/plugins/catalog/auth/azure-auth \
        command="vault-plugin-auth-azure" \
        sha256="..."
    
  2. Enable the azure auth method as a plugin:

    $ vault auth enable -path=azure azure-auth
    
    $ vault auth enable -path=azure azure-auth
    

»Azure Debug Logs

The Azure auth plugin supports debug logging which includes additional information about requests and responses from the Azure API.

To enable the Azure debug logs, set the following environment variable on the Vault server:

AZURE_GO_SDK_LOG_LEVEL=DEBUG
AZURE_GO_SDK_LOG_LEVEL=DEBUG

»API

The Azure Auth Plugin has a full HTTP API. Please see the API documentation for more details.

»Code Example

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.
func getSecretWithAzureAuth() (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.
func getSecretWithAzureAuth() (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
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using VaultSharp;
using VaultSharp.V1.AuthMethods;
using VaultSharp.V1.AuthMethods.Azure;
using VaultSharp.V1.Commons;

namespace Examples
{
    public class AzureAuthExample
    {
        public class InstanceMetadata
        {
            public string name { get; set; }
            public string resourceGroupName { get; set; }
            public string subscriptionId { get; set; }
        }

        const string MetadataEndPoint = "http://169.254.169.254/metadata/instance?api-version=2017-08-01";
        const string 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>
        public string GetSecretWithAzureAuth()
        {
            string vaultAddr = Environment.GetEnvironmentVariable("VAULT_ADDR");
            if(String.IsNullOrEmpty(vaultAddr))
            {
                throw new System.ArgumentNullException("Vault Address");
            }

            string roleName = Environment.GetEnvironmentVariable("VAULT_ROLE");
            if(String.IsNullOrEmpty(roleName))
            {
                throw new System.ArgumentNullException("Vault Role Name");
            }

            string jwt = GetJWT();
            InstanceMetadata metadata = GetMetadata();

            IAuthMethodInfo authMethod = new AzureAuthMethodInfo(roleName: roleName, jwt: jwt, subscriptionId: metadata.subscriptionId, resourceGroupName: metadata.resourceGroupName, virtualMachineName: metadata.name);
            var vaultClientSettings = new VaultClientSettings(vaultAddr, authMethod);

            IVaultClient vaultClient = new VaultClient(vaultClientSettings);

            // We can retrieve the secret from the VaultClient object
            Secret<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>
        private InstanceMetadata GetMetadata()
        {
            HttpWebRequest metadataRequest = (HttpWebRequest)WebRequest.Create(MetadataEndPoint);
            metadataRequest.Headers["Metadata"] = "true";
            metadataRequest.Method = "GET";

            HttpWebResponse metadataResponse = (HttpWebResponse)metadataRequest.GetResponse();

            StreamReader streamResponse = new StreamReader(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>
        private string GetJWT()
        {
            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 token
            StreamReader streamResponse = new StreamReader(response.GetResponseStream());
            string stringResponse = streamResponse.ReadToEnd();
            var resultsDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(stringResponse);

            return resultsDict["access_token"];
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using VaultSharp;
using VaultSharp.V1.AuthMethods;
using VaultSharp.V1.AuthMethods.Azure;
using VaultSharp.V1.Commons;

namespace Examples
{
    public class AzureAuthExample
    {
        public class InstanceMetadata
        {
            public string name { get; set; }
            public string resourceGroupName { get; set; }
            public string subscriptionId { get; set; }
        }

        const string MetadataEndPoint = "http://169.254.169.254/metadata/instance?api-version=2017-08-01";
        const string 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>
        public string GetSecretWithAzureAuth()
        {
            string vaultAddr = Environment.GetEnvironmentVariable("VAULT_ADDR");
            if(String.IsNullOrEmpty(vaultAddr))
            {
                throw new System.ArgumentNullException("Vault Address");
            }

            string roleName = Environment.GetEnvironmentVariable("VAULT_ROLE");
            if(String.IsNullOrEmpty(roleName))
            {
                throw new System.ArgumentNullException("Vault Role Name");
            }

            string jwt = GetJWT();
            InstanceMetadata metadata = GetMetadata();

            IAuthMethodInfo authMethod = new AzureAuthMethodInfo(roleName: roleName, jwt: jwt, subscriptionId: metadata.subscriptionId, resourceGroupName: metadata.resourceGroupName, virtualMachineName: metadata.name);
            var vaultClientSettings = new VaultClientSettings(vaultAddr, authMethod);

            IVaultClient vaultClient = new VaultClient(vaultClientSettings);

            // We can retrieve the secret from the VaultClient object
            Secret<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>
        private InstanceMetadata GetMetadata()
        {
            HttpWebRequest metadataRequest = (HttpWebRequest)WebRequest.Create(MetadataEndPoint);
            metadataRequest.Headers["Metadata"] = "true";
            metadataRequest.Method = "GET";

            HttpWebResponse metadataResponse = (HttpWebResponse)metadataRequest.GetResponse();

            StreamReader streamResponse = new StreamReader(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>
        private string GetJWT()
        {
            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 token
            StreamReader streamResponse = new StreamReader(response.GetResponseStream());
            string stringResponse = streamResponse.ReadToEnd();
            var resultsDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(stringResponse);

            return resultsDict["access_token"];
        }
    }
}
github logoEdit this page
DocsAPILearnCommunityPrivacySecurityPress KitConsent Manager