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
    • Seal Wrap / FIPS 140-2
    • 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

»Developer Quick Start

This quick start will explore how to use Vault client libraries inside your application code to store and retrieve your first secret value. Vault takes the security burden away from developers by providing a secure, centralized secret store for an application’s sensitive data: credentials, certificates, encryption keys, and more.

For an out-of-the-box runnable demo application showcasing these concepts and more, see the hello-vault repositories (Go, C# and Java/Spring Boot).

»Prerequisites

  • Docker or a local installation of the Vault binary
  • A development environment applicable to one of the languages in this quick start (currently Go, Ruby, C#, Python, and Java (Spring))

»Step 1: Start Vault

Warning: This in-memory “dev” server is useful for practicing with Vault locally for the first time, but is insecure and should never be used in production. For developers who need to manage their own production Vault installations, this page provides some guidance on how to make your setup more production-friendly.

Run the Vault server in a non-production "dev" mode in one of the following ways:

For Docker users, run this command:

$ docker run -p 8200:8200 -e 'VAULT_DEV_ROOT_TOKEN_ID=dev-only-token' vault
$ docker run -p 8200:8200 -e 'VAULT_DEV_ROOT_TOKEN_ID=dev-only-token' vault

For non-Docker users, run this command:

$ vault server -dev -dev-root-token-id="dev-only-token"
$ vault server -dev -dev-root-token-id="dev-only-token"

The -dev-root-token-id flag for dev servers tells the Vault server to allow full root access to anyone who presents a token with the specified value (in this case "dev-only-token").

Warning: The root token is useful for development, but allows full access to all data and functionality of Vault, so it must be carefully guarded in production. Ideally, even an administrator of Vault would use their own token with limited privileges instead of the root token.

Vault is now listening over HTTP on port 8200. With all the setup out of the way, it's time to get coding!

»Step 2: Install a client library

To read and write secrets in your application, you need to first configure a client to connect to Vault. Let's install the Vault client library for your language of choice.

Note: Some of these libraries are currently community-maintained.

Go (official) client library:

$ go get github.com/hashicorp/vault/api
$ go get github.com/hashicorp/vault/api

Now, let's add the import statements for the client library to the top of the file.

import vault "github.com/hashicorp/vault/api"
import statements for client library
1import vault "github.com/hashicorp/vault/api"

»Step 3: Authenticate to Vault

A variety of authentication methods can be used to prove your application's identity to the Vault server. To explore more secure authentication methods, such as via Kubernetes or your cloud provider, see the auth code snippets in the vault-examples repository.

To keep things simple for our example, we'll just use the root token created in Step 1. Paste the following code to initialize a new Vault client that will use token-based authentication for all its requests:

initialize a new vault client
initialize a new vault client
Go
  • Go
  • Ruby
  • C#
  • Python
  • Java
config := vault.DefaultConfig()

config.Address = "http://127.0.0.1:8200"

client, err := vault.NewClient(config)
if err != nil {
    log.Fatalf("unable to initialize Vault client: %v", err)
}

client.SetToken("dev-only-token")
1 2 3 4 5 6 7 8 9 10config := vault.DefaultConfig()

config.Address = "http://127.0.0.1:8200"

client, err := vault.NewClient(config)
if err != nil {
    log.Fatalf("unable to initialize Vault client: %v", err)
}

client.SetToken("dev-only-token")
Vault.configure do |config|
    config.address = "http://127.0.0.1:8200"
    config.token = "dev-only-token"
end
1234Vault.configure do |config|
    config.address = "http://127.0.0.1:8200"
    config.token = "dev-only-token"
end
IAuthMethodInfo authMethod = new TokenAuthMethodInfo(vaultToken: "dev-only-token");

VaultClientSettings vaultClientSettings = new
VaultClientSettings("http://127.0.0.1:8200", authMethod);
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
12345IAuthMethodInfo authMethod = new TokenAuthMethodInfo(vaultToken: "dev-only-token");

VaultClientSettings vaultClientSettings = new
VaultClientSettings("http://127.0.0.1:8200", authMethod);
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
client = hvac.Client(
    url='http://127.0.0.1:8200',
    token='dev-only-token',
)
1234client = hvac.Client(
    url='http://127.0.0.1:8200',
    token='dev-only-token',
)
VaultEndpoint vaultEndpoint = new VaultEndpoint();

vaultEndpoint.setHost("127.0.0.1");
vaultEndpoint.setPort(8200);
vaultEndpoint.setScheme("http");

VaultTemplate vaultTemplate = new VaultTemplate(
    vaultEndpoint,
    new TokenAuthentication("dev-only-token")
);
1 2 3 4 5 6 7 8 9 10VaultEndpoint vaultEndpoint = new VaultEndpoint();

vaultEndpoint.setHost("127.0.0.1");
vaultEndpoint.setPort(8200);
vaultEndpoint.setScheme("http");

VaultTemplate vaultTemplate = new VaultTemplate(
    vaultEndpoint,
    new TokenAuthentication("dev-only-token")
);

»Step 4: Store a secret

Secrets are sensitive data like API keys and passwords that we shouldn’t be storing in our code or configuration files. Instead, we want to store values like this in Vault.

We'll use the Vault client we just initialized to write a secret to Vault, like so:

write a secret to vault
write a secret to vault
Go
  • Go
  • Ruby
  • C#
  • Python
  • Java
secretData := map[string]interface{}{
    "data": map[string]interface{}{
        "password": "Hashi123",
    },
}


_, err = client.Logical().Write("secret/data/my-secret-password", secretData)
if err != nil {
    log.Fatalf("unable to write secret: %v", err)
}

fmt.Println("Secret written successfully.")
1 2 3 4 5 6 7 8 9 10111213secretData := map[string]interface{}{
    "data": map[string]interface{}{
        "password": "Hashi123",
    },
}


_, err = client.Logical().Write("secret/data/my-secret-password", secretData)
if err != nil {
    log.Fatalf("unable to write secret: %v", err)
}

fmt.Println("Secret written successfully.")
secret_data = {data: {password: "Hashi123"}}
Vault.logical.write("secret/data/my-secret-password", secret_data)

puts "Secret written successfully."
1234secret_data = {data: {password: "Hashi123"}}
Vault.logical.write("secret/data/my-secret-password", secret_data)

puts "Secret written successfully."
var secretData = new Dictionary<string, object> { { "password", "Hashi123" } };
vaultClient.V1.Secrets.KeyValue.V2.WriteSecretAsync(
    path: "/my-secret-password",
    data: secretData,
    mountPoint: "secret"
).Wait();

Console.WriteLine("Secret written successfully.");
12345678var secretData = new Dictionary<string, object> { { "password", "Hashi123" } };
vaultClient.V1.Secrets.KeyValue.V2.WriteSecretAsync(
    path: "/my-secret-password",
    data: secretData,
    mountPoint: "secret"
).Wait();

Console.WriteLine("Secret written successfully.");
create_response = client.secrets.kv.v2.create_or_update_secret(
    path='my-secret-password',
    secret=dict(password='Hashi123'),
)

print('Secret written successfully.')
123456create_response = client.secrets.kv.v2.create_or_update_secret(
    path='my-secret-password',
    secret=dict(password='Hashi123'),
)

print('Secret written successfully.')
Map<String, String> data = new HashMap<>();
data.put("password", "Hashi123");

Versioned.Metadata createResponse = vaultTemplate
    .opsForVersionedKeyValue("secret")
    .put("my-secret-password", data);

System.out.println("Secret written successfully.");
12345678Map<String, String> data = new HashMap<>();
data.put("password", "Hashi123");

Versioned.Metadata createResponse = vaultTemplate
    .opsForVersionedKeyValue("secret")
    .put("my-secret-password", data);

System.out.println("Secret written successfully.");

A common way of storing secrets is as key-value pairs using the KV secrets engine (v2). In the code we've just added, password is the key in the key-value pair, and Hashi123 is the value.

We also provided the path to our secret in Vault. We will reference this path in a moment when we learn how to retrieve our secret.

Run the code now, and you should see Secret written successfully. If not, check that you've used the correct value for the root token and Vault server address.

»Step 5: Retrieve a secret

Now that we know how to write a secret, let's practice reading one.

Underneath the line where you wrote a secret to Vault, let's add a few more lines, where we will be retrieving the secret and unpacking the value:

read a secret
read a secret
Go
  • Go
  • Ruby
  • C#
  • Python
  • Java
secret, err := client.Logical().Read("secret/data/my-secret-password")
if err != nil {
    log.Fatalf("unable to read secret: %v", err)
}

data, ok := secret.Data["data"].(map[string]interface{})
if !ok {
    log.Fatalf("data type assertion failed: %T %#v", secret.Data["data"], secret.Data["data"])
}

key := "password"
value, ok := data[key].(string)
if !ok {
    log.Fatalf("value type assertion failed: %T %#v", data[key], data[key])
}
1 2 3 4 5 6 7 8 9 101112131415secret, err := client.Logical().Read("secret/data/my-secret-password")
if err != nil {
    log.Fatalf("unable to read secret: %v", err)
}

data, ok := secret.Data["data"].(map[string]interface{})
if !ok {
    log.Fatalf("data type assertion failed: %T %#v", secret.Data["data"], secret.Data["data"])
}

key := "password"
value, ok := data[key].(string)
if !ok {
    log.Fatalf("value type assertion failed: %T %#v", data[key], data[key])
}
secret = Vault.logical.read("secret/data/my-secret-password")
password = secret.data[:data][:password]
12secret = Vault.logical.read("secret/data/my-secret-password")
password = secret.data[:data][:password]
Secret<SecretData> secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(
    path: "/my-secret-password",
    mountPoint: "secret"
).Result;

var password = secret.Data.Data["password"];
123456Secret<SecretData> secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(
    path: "/my-secret-password",
    mountPoint: "secret"
).Result;

var password = secret.Data.Data["password"];
read_response = client.secrets.kv.read_secret_version(path='my-secret-password')

password = read_response['data']['data']['password']
123read_response = client.secrets.kv.read_secret_version(path='my-secret-password')

password = read_response['data']['data']['password']
Versioned<Map<String, Object>> readResponse = vaultTemplate
    .opsForVersionedKeyValue("secret")
    .get("my-secret-password");

String password = "";
if (readResponse != null && readResponse.hasData()) {
    password = (String) readResponse.getData().get("password");
}
12345678Versioned<Map<String, Object>> readResponse = vaultTemplate
    .opsForVersionedKeyValue("secret")
    .get("my-secret-password");

String password = "";
if (readResponse != null && readResponse.hasData()) {
    password = (String) readResponse.getData().get("password");
}

Last, confirm that the value we unpacked from the read response is correct:

confirm value
confirm value
Go
  • Go
  • Ruby
  • C#
  • Python
  • Java
if value != "Hashi123" {
    log.Fatalf("unexpected password value %q retrieved from vault", value)
}

fmt.Println("Access granted!")
12345if value != "Hashi123" {
    log.Fatalf("unexpected password value %q retrieved from vault", value)
}

fmt.Println("Access granted!")
abort "Unexpected password" if password != "Hashi123"

puts "Access granted!"
123abort "Unexpected password" if password != "Hashi123"

puts "Access granted!"
if (password.ToString() != "Hashi123")
{
    throw new System.Exception("Unexpected password");
}

Console.WriteLine("Access granted!");
123456if (password.ToString() != "Hashi123")
{
    throw new System.Exception("Unexpected password");
}

Console.WriteLine("Access granted!");
if password != 'Hashi123':
    sys.exit('unexpected password')

print('Access granted!')
1234if password != 'Hashi123':
    sys.exit('unexpected password')

print('Access granted!')
if (!password.equals("Hashi123")) {
    throw new Exception("Unexpected password");
}

System.out.println("Access granted!");
12345if (!password.equals("Hashi123")) {
    throw new Exception("Unexpected password");
}

System.out.println("Access granted!");

If the secret was fetched successfully, you should see the Access granted! message after you run the code. If not, check to see if you provided the correct path to your secret.

That's it! You've just written and retrieved your first Vault secret!

The complete code samples for the steps you've just performed in this quick start are available here:

  • Go
  • Ruby
  • C#
  • Python
  • Java (Spring)

»Additional examples

For more secure examples of client authentication, see the auth snippets in the vault-examples repo.

For a runnable demo app that demonstrates more features, for example, how to keep your connection to Vault alive and how to connect to a database using Vault's dynamic database credentials, see the sample application hello-vault (Go, C#).

To learn how to integrate applications with Vault without needing to always change your application code, see the Vault Agent documentation.

github logoEdit this page
DocsAPILearnCommunityPrivacySecurityPress KitConsent Manager