vault page title Username Templating Username templating Username templating are used in some secret engines to allow operators to define layout docs how dynamic usernames are generated

Answer:
---
layout: docs
page_title: Username Templating
description: >-
  Username templating are used in some secret engines to allow operators to define
  how dynamic usernames are generated.
---

# Username templating

Some of the secrets engines that generate dynamic users for external systems provide the ability for Vault operators
to customize how usernames are generated for said external systems. This customization feature uses the
[Go template language](https://golang.org/pkg/text/template/). This page describes the basics of using these templates
for username generation but does not go into great depth of using the templating language for more advanced usages.
See the API documentation for the given secret engine to determine if it supports username templating and for more
details on using it with that engine.

~> When customizing how usernames are generated, take care to ensure you have enough randomness to ensure uniqueness
otherwise multiple calls to create the credentials may interfere with each other.

In addition to the functionality built into the Go template language, a number of additional functions are available:

## Available functions

### String/Character manipulation

`lowercase` - Lowercases the input value.

**Example**: ``

`replace` - Find/replace on the input value.

**Example**: ``

`truncate` - truncates the input value to the specified number of characters.

**Example**: ``

`truncate_sha256` - Truncates the input value to the specified number of characters. The last 8 characters of the
new value will be replace by the first 8 characters of the SHA256 hash of the truncated characters.

**Example**: ``. If `FieldName` is `abcdefghijklmnopqrstuvwxyz`, all characters after
the 12th (`l`) are removed and SHA256 hashed (`872808ffbf...1886ca6f20`).
The first 8 characters of the hash (`872808ff`) are then appended to the end of the first 12 characters from the
original value: `abcdefghijkl872808ff`.

`uppercase` - Uppercases the input value.

**Example**: ``

### Generating values

`random` - Generates a random string from lowercase letters, uppercase letters, and numbers. Must include a
number indicating how many characters to generate.

**Example**: `` generates 20 random characters

`timestamp` - The current time. Must provide a formatting string based on Go’s [time package](https://golang.org/pkg/time/).

**Example**: ``

`unix_time` - The current unix timestamp (number of seconds since Jan 1 1970).

**Example**: ``

`unix_time_millis` - The current unix timestamp in milliseconds.

**Example**: ``

`uuid` - Generates a random UUID.

**Example**: ``

### Hashing

`base64` - Base64 encodes the input value.

**Example**: ``

`sha256` - SHA256 hashes the input value.

**Example**: ``

## Examples

Each secret engine provides a different set of data to the template. Please see the associated secret engine's
documentation for details on what values are provided to the template. The examples below are modeled after the
[Database engine's](/vault/docs/secrets/databases) data, however the specific fields that are provided from a given engine
may differ from these examples. Additionally, the time is assumed to be 2009-02-13 11:31:30PM GMT
(unix timestamp: 1234567890) and random characters are the ordered english alphabet: `abcdefghijklmnopqrstuvwxyz`.

-> Note: The space between `` and the values/functions are optional.
For instance: `` is equivalent to ``

| Field name    | Value                     |
| ------------- | ------------------------- |
| `DisplayName` | `token-with-display-name` |
| `RoleName`    | `my_custom_database_role` |

To reference either of these fields, a `.` must be put in front of the field name: ``. Custom functions
do not include a `.` in front of them: ``.

### Basic example

**Template**:

```
_
```

**Username**:

```
token-with-display-name_my_custom_database_role
```

This is a basic example that references the two fields that are provided to the template. In simplest terms, this is
a simple string substitution.

~> This example does not have any randomness and should not be used when generating dynamic usernames. The purpose is to
demonstrate referencing data within the Go template language.

### Custom functions

**Template**:

```
FOO___
```

**Username**:

```
FOO_TOKEN_WITH_DISPLAY_NAME_MY_CUSTOM_DATABASE_ROLE_2009_02_13T11_31_30Z_0700
```

`` - Replaces all dashes with underscores and then uppercases the display name.

`` - Replaces all dashes with underscores and then uppercases the role name.

`` - Generates the current timestamp using the provided format and
replaces all dashes with underscores.

### Truncating to maximum length

**Template**:

```

```

**Username**:

```
v_token-wi_my_custo_abcdefghijklmnopqrst_1234
```

`.DisplayName | truncate 8` truncates the display name to 8 characters (`token-wi`).

`.RoleName | truncate 8` truncates the role name to 8 characters (`my_custo`).

`random 20` generates 20 random characters `abcdefghijklmnopqrst`.

`unix_time` generates the current timestamp as the number of seconds since January 1, 1970 (`1234567890`).

Each of these values are passed to `printf "v_%s_%s_%s_%s"` which prepends them with `v_` and puts an underscore between
each field. This results in `v_token-wi_my_custo_abcdefghijklmnopqrst_1234567890`. This value is then passed to
`truncate 45` where the last 6 characters are removed which results in `v_token-wi_my_custo_abcdefghijklmnopqrst_1234`.

## Tutorial

Refer to the [Database secrets
engine](/vault/tutorials/db-credentials/database-secrets#define-a-username-template) for step-by-step instructions.

layout  docs page title  Username Templating description       Username templating are used in some secret engines to allow operators to define   how dynamic usernames are generated         Username templating  Some of the secrets engines that generate dynamic users for external systems provide the ability for Vault operators to customize how usernames are generated for said external systems  This customization feature uses the  Go template language  https   golang org pkg text template    This page describes the basics of using these templates for username generation but does not go into great depth of using the templating language for more advanced usages  See the API documentation for the given secret engine to determine if it supports username templating and for more details on using it with that engine      When customizing how usernames are generated  take care to ensure you have enough randomness to ensure uniqueness otherwise multiple calls to create the credentials may interfere with each other   In addition to the functionality built into the Go template language  a number of additional functions are available      Available functions      String Character manipulation   lowercase    Lowercases the input value  br     Example         replace    Find replace on the input value  br     Example         truncate    truncates the input value to the specified number of characters  br     Example         truncate sha256    Truncates the input value to the specified number of characters  The last 8 characters of the new value will be replace by the first 8 characters of the SHA256 hash of the truncated characters  br     Example        If  FieldName  is  abcdefghijklmnopqrstuvwxyz   all characters after the 12th   l   are removed and SHA256 hashed   872808ffbf   1886ca6f20    The first 8 characters of the hash   872808ff   are then appended to the end of the first 12 characters from the original value   abcdefghijkl872808ff     uppercase    Uppercases the input value  br     Example            Generating values   random    Generates a random string from lowercase letters  uppercase letters  and numbers  Must include a number indicating how many characters to generate  br     Example       generates 20 random characters   timestamp    The current time  Must provide a formatting string based on Go s  time package  https   golang org pkg time    br     Example         unix time    The current unix timestamp  number of seconds since Jan 1 1970   br     Example         unix time millis    The current unix timestamp in milliseconds  br     Example         uuid    Generates a random UUID  br     Example            Hashing   base64    Base64 encodes the input value  br     Example         sha256    SHA256 hashes the input value  br     Example           Examples  Each secret engine provides a different set of data to the template  Please see the associated secret engine s documentation for details on what values are provided to the template  The examples below are modeled after the  Database engine s   vault docs secrets databases  data  however the specific fields that are provided from a given engine may differ from these examples  Additionally  the time is assumed to be 2009 02 13 11 31 30PM GMT  unix timestamp  1234567890  and random characters are the ordered english alphabet   abcdefghijklmnopqrstuvwxyz       Note  The space between    and the values functions are optional  For instance     is equivalent to       Field name      Value                                                                        DisplayName     token with display name       RoleName        my custom database role     To reference either of these fields  a     must be put in front of the field name      Custom functions do not include a     in front of them           Basic example    Template                  Username         token with display name my custom database role      This is a basic example that references the two fields that are provided to the template  In simplest terms  this is a simple string substitution      This example does not have any randomness and should not be used when generating dynamic usernames  The purpose is to demonstrate referencing data within the Go template language       Custom functions    Template         FOO           Username         FOO TOKEN WITH DISPLAY NAME MY CUSTOM DATABASE ROLE 2009 02 13T11 31 30Z 0700           Replaces all dashes with underscores and then uppercases the display name  br        Replaces all dashes with underscores and then uppercases the role name  br        Generates the current timestamp using the provided format and replaces all dashes with underscores       Truncating to maximum length    Template                 Username         v token wi my custo abcdefghijklmnopqrst 1234        DisplayName   truncate 8  truncates the display name to 8 characters   token wi    br     RoleName   truncate 8  truncates the role name to 8 characters   my custo    br    random 20  generates 20 random characters  abcdefghijklmnopqrst   br    unix time  generates the current timestamp as the number of seconds since January 1  1970   1234567890    br    Each of these values are passed to  printf  v  s  s  s  s   which prepends them with  v   and puts an underscore between each field  This results in  v token wi my custo abcdefghijklmnopqrst 1234567890   This value is then passed to  truncate 45  where the last 6 characters are removed which results in  v token wi my custo abcdefghijklmnopqrst 1234       Tutorial  Refer to the  Database secrets engine   vault tutorials db credentials database secrets define a username template  for step by step instructions


vault page title Tokens Warning heading Internal token structure is volatile Tokens are a core auth method in Vault Concepts and important features Tokens are opaque values so their structure is undocumented and subject to change layout docs Tokens

Answer:
---
layout: docs
page_title: Tokens
description: Tokens are a core auth method in Vault. Concepts and important features.
---

# Tokens

<Warning heading="Internal token structure is volatile">
  Tokens are opaque values so their structure is undocumented and subject to change.
  Scripts and automations that rely on the internal structure of a token in scripts will break.
</Warning>

Tokens are the core method for _authentication_ within Vault. Tokens
can be used directly or [auth methods](/vault/docs/concepts/auth)
can be used to dynamically generate tokens based on external identities.

If you've gone through the getting started guide, you probably noticed that
`vault server -dev` (or `vault operator init` for a non-dev server) outputs an
initial "root token." This is the first method of authentication for Vault.
It is also the only auth method that cannot be disabled.

As stated in the [authentication concepts](/vault/docs/concepts/auth),
all external authentication mechanisms, such as GitHub, map down to dynamically
created tokens. These tokens have all the same properties as a normal manually
created token.

Within Vault, tokens map to information. The most important information mapped
to a token is a set of one or more attached
[policies](/vault/docs/concepts/policies). These policies control what the token
holder is allowed to do within Vault. Other mapped information includes
metadata that can be viewed and is added to the audit log, such as creation
time, last renewal time, and more.

Read on for a deeper dive into token concepts.  See the
[tokens tutorial](/vault/tutorials/tokens/tokens)
for details on how these concepts play out in practice.

## Token types

There are three types of tokens. On this page `service` tokens and `batch` tokens are outlined,
while `recovery` tokens are covered separately in their [own page](/vault/docs/concepts/recovery-mode#recovery-tokens).
A section near the bottom of this page contains detailed information about their differences,
but it is useful to understand other token concepts first. The features in the following
sections all apply to service tokens, and their applicability to batch tokens is discussed
later.

### Token prefixes

Tokens have a specific prefix that indicates their type. As of Vault 1.10, this token
format was updated. The following table lists the prefix differences. This format
pattern and its change also apply for recovery tokens. After the prefix, a string of
24 or more randomly-generated characters is appended.

| Token Type      | Vault 1.9.x or earlier | Vault 1.10 and later |
|-----------------|------------------------|----------------------|
| Service tokens  | `s.<random>`           | `hvs.<random>`       |
| Batch tokens    | `b.<random>`           | `hvb.<random>`       |
| Recovery tokens | `r.<random>`           | `hvr.<random>`       |

For example, a service token may look like `hvs.CvmS4c0DPTvHv5eJgXWMJg9r`.

## The token store

Often in documentation or in help channels, the "token store" is referenced.
This is the same as the [`token` authentication
backend](/vault/docs/auth/token). This is a special
backend in that it is responsible for creating and storing tokens, and cannot
be disabled. It is also the only auth method that has no login
capability -- all actions require existing authenticated tokens.

## Root tokens

Root tokens are tokens that have the `root` policy attached to them. Root
tokens can do anything in Vault. _Anything_. In addition, they are the only
type of token within Vault that can be set to never expire without any renewal
needed. As a result, it is purposefully hard to create root tokens; in fact
there are only three ways to create root tokens:

1. The initial root token generated at `vault operator init` time -- this token has no
   expiration
1. By using another root token; a root token with an expiration cannot create a
   root token that never expires
1. By using `vault operator generate-root` ([example](/vault/tutorials/operations/generate-root))
   with the permission of a quorum of unseal key holders

Root tokens are useful in development but should be extremely carefully guarded
in production. In fact, the Vault team recommends that root tokens are only
used for just enough initial setup (usually, setting up auth methods
and policies necessary to allow administrators to acquire more limited tokens)
or in emergencies, and are revoked immediately after they are no longer needed.
If a new root token is needed, the `operator generate-root` command and associated
[API endpoint](/vault/api-docs/system/generate-root) can be used to generate one on-the-fly.

It is also good security practice for there to be multiple eyes on a terminal
whenever a root token is live. This way multiple people can verify as to the
tasks performed with the root token, and that the token was revoked immediately
after these tasks were completed.

## Token hierarchies and orphan tokens

Normally, when a token holder creates new tokens, these tokens will be created
as children of the original token; tokens they create will be children of them;
and so on. When a parent token is revoked, all of its child tokens -- and all
of their leases -- are revoked as well. This ensures that a user cannot escape
revocation by simply generating a never-ending tree of child tokens.

Often this behavior is not desired, so users with appropriate access can create
`orphan` tokens. These tokens have no parent -- they are the root of their own
token tree. These orphan tokens can be created:

1. Via `write` access to the `auth/token/create-orphan` endpoint
1. By having `sudo` or `root` access to the `auth/token/create`
   and setting the `no_parent` parameter to `true`
1. Via token store roles
1. By logging in with any other (non-`token`) auth method

Users with appropriate permissions can also use the `auth/token/revoke-orphan`
endpoint, which revokes the given token but rather than revoke the rest of the
tree, it instead sets the tokens' immediate children to be orphans. Use with
caution!

## Token accessors

When tokens are created, a token accessor is also created and returned. This
accessor is a value that acts as a reference to a token and can only be used to
perform limited actions:

1. Look up a token's properties (not including the actual token ID)
1. Look up a token's capabilities on a path
1. Renew the token
1. Revoke the token

The token _making the call_, _not_ the token associated with the accessor, must
have appropriate permissions for these functions.

There are many useful workflows around token accessors. As an example, a
service that creates tokens on behalf of another service (such as the
[Nomad](https://www.nomadproject.io/) scheduler) can store the accessor
correlated with a particular job ID. When the job is complete, the accessor can
be used to instantly revoke the token given to the job and all of its leased
credentials, limiting the chance that a bad actor will discover and use them.

Audit devices can optionally be set to not obfuscate token accessors in audit
logs. This provides a way to quickly revoke tokens in case of an emergency.
However, it also means that the audit logs can be used to perform a larger-scale
denial of service attack.

Finally, the only way to "list tokens" is via the `auth/token/accessors`
command, which actually gives a list of token accessors. While this is still a
dangerous endpoint (since listing all of the accessors means that they can then
be used to revoke all tokens), it also provides a way to audit and revoke the
currently-active set of tokens.

## Token Time-To-Live, periodic tokens, and explicit max TTLs

Every non-root token has a time-to-live (TTL) associated with it, which is a
current period of validity since either the token's creation time or last
renewal time, whichever is more recent. (Root tokens may have a TTL associated,
but the TTL may also be 0, indicating a token that never expires). After the
current TTL is up, the token will no longer function -- it, and its associated
leases, are revoked.

If the token is renewable, Vault can be asked to extend the token validity
period using `vault token renew` or the appropriate renewal endpoint. At this
time, various factors come into play. What happens depends upon whether the
token is a periodic token (available for creation by `root`/`sudo` users, token
store roles, or some auth methods), has an explicit maximum TTL
attached, or neither.

### The general case

In the general case, where there is neither a period nor explicit maximum TTL
value set on the token, the token's lifetime since it was created will be
compared to the maximum TTL. This maximum TTL value is dynamically generated
and can change from renewal to renewal, so the value cannot be displayed when a
token's information is looked up. It is based on a combination of factors:

1. The system max TTL, which is 32 days but can be changed in Vault's
   configuration file.
1. The max TTL set on a mount using [mount
   tuning](/vault/api-docs/system/mounts). This value
   is allowed to override the system max TTL -- it can be longer or shorter,
   and if set this value will be respected.
1. A value suggested by the auth method that issued the token. This
   might be configured on a per-role, per-group, or per-user basis. This value
   is allowed to be less than the mount max TTL (or, if not set, the system max
   TTL), but it is not allowed to be longer.

Note that the values in (2) and (3) may change at any given time, which is why
a final determination about the current allowed max TTL is made at renewal time
using the current values. It is also why it is important to always ensure that
the TTL returned from a renewal operation is within an allowed range; if this
value is not extending, likely the TTL of the token cannot be extended past its
current value and the client may want to reauthenticate and acquire a new
token. However, outside of direct operator interaction, Vault will never revoke
a token before the returned TTL has expired.

### Explicit max TTLs

Tokens can have an explicit max TTL set on them. This value becomes a hard
limit on the token's lifetime -- no matter what the values in (1), (2), and (3)
from the general case are, the token cannot live past this explicitly-set
value. This has an effect even when using periodic tokens to escape the normal
TTL mechanism.

### Periodic tokens

In some cases, having a token be revoked would be problematic -- for instance,
if a long-running service needs to maintain its SQL connection pool over a long
period of time. In this scenario, a periodic token can be used. Periodic tokens
can be created in a few ways:

1. By having `sudo` capability or a `root` token with the `auth/token/create`
   endpoint
1. By using token store roles
1. By using an auth method that supports issuing these, such as
   AppRole

At issue time, the TTL of a periodic token will be equal to the configured
period. At every renewal time, the TTL will be reset back to this configured
period, and as long as the token is successfully renewed within each of these
periods of time, it will never expire. Outside of `root` tokens, it is
currently the only way for a token in Vault to have an unlimited lifetime.

The idea behind periodic tokens is that it is easy for systems and services to
perform an action relatively frequently -- for instance, every two hours, or
even every five minutes. Therefore, as long as a system is actively renewing
this token -- in other words, as long as the system is alive -- the system is
allowed to keep using the token and any associated leases. However, if the
system stops renewing within this period (for instance, if it was shut down),
the token will expire relatively quickly. It is good practice to keep this
period as short as possible, and generally speaking it is not useful for humans
to be given periodic tokens.

There are a few important things to know when using periodic tokens:

- When a periodic token is created via a token store role, the _current_ value
  of the role's period setting will be used at renewal time
- A token with both a period and an explicit max TTL will act like a periodic
  token but will be revoked when the explicit max TTL is reached

## CIDR-Bound tokens

Some tokens are able to be bound to CIDR(s) that restrict the range of client
IPs allowed to use them. These affect all tokens except for non-expiring root
tokens (those with a TTL of zero). If a root token has an expiration, it also
is affected by CIDR-binding.

## Token types in detail

There are currently two types of tokens.

### Service tokens

Service tokens are what users will generally think of as "normal" Vault tokens.
They support all features, such as renewal, revocation, creating child tokens,
and more. They are correspondingly heavyweight to create and track.

### Batch tokens

Batch tokens are encrypted blobs that carry enough information for them to
be used for Vault actions, but they require no storage on disk to track them.
As a result they are extremely lightweight and scalable, but lack most of the
flexibility and features of service tokens.

### Token type comparison

This reference chart describes the difference in behavior between service and
batch tokens.

|                                                     |                                          Service Tokens |                                    Batch Tokens |
| --------------------------------------------------- | ------------------------------------------------------: | ----------------------------------------------: |
| Can Be Root Tokens                                  |                                                     Yes |                                              No |
| Can Create Child Tokens                             |                                                     Yes |                                              No |
| Can be Renewable                                    |                                                     Yes |                                              No |
| Manually Revocable                                  |                                                     Yes |                                              No |
| Can be Periodic                                     |                                                     Yes |                                              No |
| Can have Explicit Max TTL                           |                                                     Yes |                    No (always uses a fixed TTL) |
| Has Accessors                                       |                                                     Yes |                                              No |
| Has Cubbyhole                                       |                                                     Yes |                                              No |
| Revoked with Parent (if not orphan)                 |                                                     Yes |                                   Stops Working |
| Dynamic Secrets Lease Assignment                    |                                                    Self |                          Parent (if not orphan) |
| Can be Used Across Performance Replication Clusters |                                                      No |                                 Yes (if orphan) |
| Creation Scales with Performance Standby Node Count |                                                      No |                                             Yes |
| Cost                                                | Heavyweight; multiple storage writes per token creation | Lightweight; no storage cost for token creation |

### Service vs. batch token lease handling

#### Service tokens

Leases created by service tokens (including child tokens' leases) are tracked
along with the service token and revoked when the token expires.

#### Batch tokens

Leases created by batch tokens are constrained to the remaining TTL of the
batch tokens and, if the batch token is not an orphan, are tracked by the
parent. They are revoked when the batch token's TTL expires, or when the batch
token's parent is revoked (at which point the batch token is also denied access
to Vault).

As a corollary, batch tokens can be used across performance replication
clusters, but only if they are orphan, since non-orphan tokens will not be able
to ensure the validity of the parent token.

## Error Responses

When using a token that has been revoked, exceeded its TTL, or is an otherwise invalid value, Vault will respond
with a `403` response code error containing the following error messages: `invalid token` and `permission denied`.

When using a token with incorrect policy access, Vault will respond with a `403` response code error containing the error message
`permission denied`.

layout  docs page title  Tokens description  Tokens are a core auth method in Vault  Concepts and important features         Tokens   Warning heading  Internal token structure is volatile     Tokens are opaque values so their structure is undocumented and subject to change    Scripts and automations that rely on the internal structure of a token in scripts will break    Warning   Tokens are the core method for  authentication  within Vault  Tokens can be used directly or  auth methods   vault docs concepts auth  can be used to dynamically generate tokens based on external identities   If you ve gone through the getting started guide  you probably noticed that  vault server  dev   or  vault operator init  for a non dev server  outputs an initial  root token   This is the first method of authentication for Vault  It is also the only auth method that cannot be disabled   As stated in the  authentication concepts   vault docs concepts auth   all external authentication mechanisms  such as GitHub  map down to dynamically created tokens  These tokens have all the same properties as a normal manually created token   Within Vault  tokens map to information  The most important information mapped to a token is a set of one or more attached  policies   vault docs concepts policies   These policies control what the token holder is allowed to do within Vault  Other mapped information includes metadata that can be viewed and is added to the audit log  such as creation time  last renewal time  and more   Read on for a deeper dive into token concepts   See the  tokens tutorial   vault tutorials tokens tokens  for details on how these concepts play out in practice      Token types  There are three types of tokens  On this page  service  tokens and  batch  tokens are outlined  while  recovery  tokens are covered separately in their  own page   vault docs concepts recovery mode recovery tokens   A section near the bottom of this page contains detailed information about their differences  but it is useful to understand other token concepts first  The features in the following sections all apply to service tokens  and their applicability to batch tokens is discussed later       Token prefixes  Tokens have a specific prefix that indicates their type  As of Vault 1 10  this token format was updated  The following table lists the prefix differences  This format pattern and its change also apply for recovery tokens  After the prefix  a string of 24 or more randomly generated characters is appended     Token Type        Vault 1 9 x or earlier   Vault 1 10 and later                                                                         Service tokens     s  random                hvs  random             Batch tokens       b  random                hvb  random             Recovery tokens    r  random                hvr  random            For example  a service token may look like  hvs CvmS4c0DPTvHv5eJgXWMJg9r       The token store  Often in documentation or in help channels  the  token store  is referenced  This is the same as the   token  authentication backend   vault docs auth token   This is a special backend in that it is responsible for creating and storing tokens  and cannot be disabled  It is also the only auth method that has no login capability    all actions require existing authenticated tokens      Root tokens  Root tokens are tokens that have the  root  policy attached to them  Root tokens can do anything in Vault   Anything   In addition  they are the only type of token within Vault that can be set to never expire without any renewal needed  As a result  it is purposefully hard to create root tokens  in fact there are only three ways to create root tokens   1  The initial root token generated at  vault operator init  time    this token has no    expiration 1  By using another root token  a root token with an expiration cannot create a    root token that never expires 1  By using  vault operator generate root    example   vault tutorials operations generate root      with the permission of a quorum of unseal key holders  Root tokens are useful in development but should be extremely carefully guarded in production  In fact  the Vault team recommends that root tokens are only used for just enough initial setup  usually  setting up auth methods and policies necessary to allow administrators to acquire more limited tokens  or in emergencies  and are revoked immediately after they are no longer needed  If a new root token is needed  the  operator generate root  command and associated  API endpoint   vault api docs system generate root  can be used to generate one on the fly   It is also good security practice for there to be multiple eyes on a terminal whenever a root token is live  This way multiple people can verify as to the tasks performed with the root token  and that the token was revoked immediately after these tasks were completed      Token hierarchies and orphan tokens  Normally  when a token holder creates new tokens  these tokens will be created as children of the original token  tokens they create will be children of them  and so on  When a parent token is revoked  all of its child tokens    and all of their leases    are revoked as well  This ensures that a user cannot escape revocation by simply generating a never ending tree of child tokens   Often this behavior is not desired  so users with appropriate access can create  orphan  tokens  These tokens have no parent    they are the root of their own token tree  These orphan tokens can be created   1  Via  write  access to the  auth token create orphan  endpoint 1  By having  sudo  or  root  access to the  auth token create     and setting the  no parent  parameter to  true  1  Via token store roles 1  By logging in with any other  non  token   auth method  Users with appropriate permissions can also use the  auth token revoke orphan  endpoint  which revokes the given token but rather than revoke the rest of the tree  it instead sets the tokens  immediate children to be orphans  Use with caution      Token accessors  When tokens are created  a token accessor is also created and returned  This accessor is a value that acts as a reference to a token and can only be used to perform limited actions   1  Look up a token s properties  not including the actual token ID  1  Look up a token s capabilities on a path 1  Renew the token 1  Revoke the token  The token  making the call    not  the token associated with the accessor  must have appropriate permissions for these functions   There are many useful workflows around token accessors  As an example  a service that creates tokens on behalf of another service  such as the  Nomad  https   www nomadproject io   scheduler  can store the accessor correlated with a particular job ID  When the job is complete  the accessor can be used to instantly revoke the token given to the job and all of its leased credentials  limiting the chance that a bad actor will discover and use them   Audit devices can optionally be set to not obfuscate token accessors in audit logs  This provides a way to quickly revoke tokens in case of an emergency  However  it also means that the audit logs can be used to perform a larger scale denial of service attack   Finally  the only way to  list tokens  is via the  auth token accessors  command  which actually gives a list of token accessors  While this is still a dangerous endpoint  since listing all of the accessors means that they can then be used to revoke all tokens   it also provides a way to audit and revoke the currently active set of tokens      Token Time To Live  periodic tokens  and explicit max TTLs  Every non root token has a time to live  TTL  associated with it  which is a current period of validity since either the token s creation time or last renewal time  whichever is more recent   Root tokens may have a TTL associated  but the TTL may also be 0  indicating a token that never expires   After the current TTL is up  the token will no longer function    it  and its associated leases  are revoked   If the token is renewable  Vault can be asked to extend the token validity period using  vault token renew  or the appropriate renewal endpoint  At this time  various factors come into play  What happens depends upon whether the token is a periodic token  available for creation by  root   sudo  users  token store roles  or some auth methods   has an explicit maximum TTL attached  or neither       The general case  In the general case  where there is neither a period nor explicit maximum TTL value set on the token  the token s lifetime since it was created will be compared to the maximum TTL  This maximum TTL value is dynamically generated and can change from renewal to renewal  so the value cannot be displayed when a token s information is looked up  It is based on a combination of factors   1  The system max TTL  which is 32 days but can be changed in Vault s    configuration file  1  The max TTL set on a mount using  mount    tuning   vault api docs system mounts   This value    is allowed to override the system max TTL    it can be longer or shorter     and if set this value will be respected  1  A value suggested by the auth method that issued the token  This    might be configured on a per role  per group  or per user basis  This value    is allowed to be less than the mount max TTL  or  if not set  the system max    TTL   but it is not allowed to be longer   Note that the values in  2  and  3  may change at any given time  which is why a final determination about the current allowed max TTL is made at renewal time using the current values  It is also why it is important to always ensure that the TTL returned from a renewal operation is within an allowed range  if this value is not extending  likely the TTL of the token cannot be extended past its current value and the client may want to reauthenticate and acquire a new token  However  outside of direct operator interaction  Vault will never revoke a token before the returned TTL has expired       Explicit max TTLs  Tokens can have an explicit max TTL set on them  This value becomes a hard limit on the token s lifetime    no matter what the values in  1    2   and  3  from the general case are  the token cannot live past this explicitly set value  This has an effect even when using periodic tokens to escape the normal TTL mechanism       Periodic tokens  In some cases  having a token be revoked would be problematic    for instance  if a long running service needs to maintain its SQL connection pool over a long period of time  In this scenario  a periodic token can be used  Periodic tokens can be created in a few ways   1  By having  sudo  capability or a  root  token with the  auth token create     endpoint 1  By using token store roles 1  By using an auth method that supports issuing these  such as    AppRole  At issue time  the TTL of a periodic token will be equal to the configured period  At every renewal time  the TTL will be reset back to this configured period  and as long as the token is successfully renewed within each of these periods of time  it will never expire  Outside of  root  tokens  it is currently the only way for a token in Vault to have an unlimited lifetime   The idea behind periodic tokens is that it is easy for systems and services to perform an action relatively frequently    for instance  every two hours  or even every five minutes  Therefore  as long as a system is actively renewing this token    in other words  as long as the system is alive    the system is allowed to keep using the token and any associated leases  However  if the system stops renewing within this period  for instance  if it was shut down   the token will expire relatively quickly  It is good practice to keep this period as short as possible  and generally speaking it is not useful for humans to be given periodic tokens   There are a few important things to know when using periodic tokens     When a periodic token is created via a token store role  the  current  value   of the role s period setting will be used at renewal time   A token with both a period and an explicit max TTL will act like a periodic   token but will be revoked when the explicit max TTL is reached     CIDR Bound tokens  Some tokens are able to be bound to CIDR s  that restrict the range of client IPs allowed to use them  These affect all tokens except for non expiring root tokens  those with a TTL of zero   If a root token has an expiration  it also is affected by CIDR binding      Token types in detail  There are currently two types of tokens       Service tokens  Service tokens are what users will generally think of as  normal  Vault tokens  They support all features  such as renewal  revocation  creating child tokens  and more  They are correspondingly heavyweight to create and track       Batch tokens  Batch tokens are encrypted blobs that carry enough information for them to be used for Vault actions  but they require no storage on disk to track them  As a result they are extremely lightweight and scalable  but lack most of the flexibility and features of service tokens       Token type comparison  This reference chart describes the difference in behavior between service and batch tokens                                                                                Service Tokens                                      Batch Tokens                                                                                Can Be Root Tokens                                                                                Yes                                                No     Can Create Child Tokens                                                                                Yes                                                No     Can be Renewable                                                                                Yes                                                No     Manually Revocable                                                                                Yes                                                No     Can be Periodic                                                                                Yes                                                No     Can have Explicit Max TTL                                                                                Yes                      No  always uses a fixed TTL      Has Accessors                                                                                Yes                                                No     Has Cubbyhole                                                                                Yes                                                No     Revoked with Parent  if not orphan                                                                        Yes                                     Stops Working     Dynamic Secrets Lease Assignment                                                                         Self                            Parent  if not orphan      Can be Used Across Performance Replication Clusters                                                        No                                   Yes  if orphan      Creation Scales with Performance Standby Node Count                                                        No                                               Yes     Cost                                                  Heavyweight  multiple storage writes per token creation   Lightweight  no storage cost for token creation        Service vs  batch token lease handling       Service tokens  Leases created by service tokens  including child tokens  leases  are tracked along with the service token and revoked when the token expires        Batch tokens  Leases created by batch tokens are constrained to the remaining TTL of the batch tokens and  if the batch token is not an orphan  are tracked by the parent  They are revoked when the batch token s TTL expires  or when the batch token s parent is revoked  at which point the batch token is also denied access to Vault    As a corollary  batch tokens can be used across performance replication clusters  but only if they are orphan  since non orphan tokens will not be able to ensure the validity of the parent token      Error Responses  When using a token that has been revoked  exceeded its TTL  or is an otherwise invalid value  Vault will respond with a  403  response code error containing the following error messages   invalid token  and  permission denied    When using a token with incorrect policy access  Vault will respond with a  403  response code error containing the error message  permission denied


vault Before performing any operation with Vault the connecting client must be Authentication authenticated layout docs page title Authentication

Answer:
---
layout: docs
page_title: Authentication
description: >-
  Before performing any operation with Vault, the connecting client must be
  authenticated.
---

# Authentication

Authentication in Vault is the process by which user or machine supplied
information is verified against an internal or external system. Vault supports
multiple [auth methods](/vault/docs/auth) including GitHub,
LDAP, AppRole, and more. Each auth method has a specific use case.

Before a client can interact with Vault, it must _authenticate_ against an
auth method. Upon authentication, a token is generated. This token is
conceptually similar to a session ID on a website. The token may have attached
policy, which is mapped at authentication time. This process is described in
detail in the [policies concepts](/vault/docs/concepts/policies) documentation.

## auth methods

Vault supports a number of auth methods. Some backends are targeted
toward users while others are targeted toward machines. Most authentication
backends must be enabled before use. To enable an auth method:

```shell-session
$ vault auth enable userpass -path=my-auth
```

This enables the "userpass" auth method at the path "my-auth". This
authentication will be accessible at the path "my-auth". Often you will see
authentications at the same path as their name, but this is not a requirement.

To learn more about this authentication, use the built-in `path-help` command:

```shell-session
$ vault path-help auth/my-auth
# ...
```

Vault supports multiple auth methods simultaneously, and you can even
mount the same type of auth method at different paths. Only one
authentication is required to gain access to Vault, and it is not currently
possible to force a user through multiple auth methods to gain
access, although some backends do support MFA.

## Tokens

There is an [entire page dedicated to tokens](/vault/docs/concepts/tokens),
but it is important to understand that authentication works by verifying
your identity and then generating a token to associate with that identity.

For example, even though you may authenticate using something like GitHub,
Vault generates a unique access token for you to use for future requests.
The CLI automatically attaches this token to requests, but if you're using
the API you'll have to do this manually.

This token given for authentication with any backend can also be used
with the full set of token commands, such as creating new sub-tokens,
revoking tokens, and renewing tokens. This is all covered on the
[token concepts page](/vault/docs/concepts/tokens).

## Authenticating

### Via the CLI

To authenticate with the CLI, `vault login` is used. This supports many
of the built-in auth methods. For example, with GitHub:

```shell-session
$ vault login -method=github token=<token>
...
```

After authenticating, you will be logged in. The CLI command will also
output your raw token. This token is used for revocation and renewal.
As the user logging in, the primary use case of the token is renewal,
covered below in the "Auth Leases" section.

To determine what variables are needed for an auth method,
supply the `-method` flag without any additional arguments and help
will be shown.

If you're using a method that isn't supported via the CLI, then the API
must be used.

### Via the API

API authentication is generally used for machine authentication. Each
auth method implements its own login endpoint. Use the `vault path-help`
mechanism to find the proper endpoint.

For example, the GitHub login endpoint is located at `auth/github/login`.
And to determine the arguments needed, `vault path-help auth/github/login` can
be used.

## Auth leases

Just like secrets, identities have
[leases](/vault/docs/concepts/lease) associated with them. This means that
you must reauthenticate after the given lease period to continue accessing
Vault.

To set the lease associated with an identity, reference the help for
the specific auth method in use. It is specific to each backend
how leasing is implemented.

And just like secrets, identities can be renewed without having to
completely reauthenticate. Just use `vault token renew <token>` with the
leased token associated with your identity to renew it.

## Code example

The following code snippet demonstrates how to renew auth tokens.

<CodeTabs heading="token renewal example">

<CodeBlockConfig lineNumbers>

```go
package main

import (
	"context"
	"fmt"
	"log"

	vault "github.com/hashicorp/vault/api"
	auth "github.com/hashicorp/vault/api/auth/userpass"
)

// Once you've set the token for your Vault client, you will need to
// periodically renew its lease.
//
// A function like this should be run as a goroutine to avoid blocking.
//
// Production applications may also wish to be more tolerant of failures and
// retry rather than exiting.
//
// Additionally, enterprise Vault users should be aware that due to eventual
// consistency, the API may return unexpected errors when running Vault with
// performance standbys or performance replication, despite the client having
// a freshly renewed token. See https://developer.hashicorp.com/vault/docs/enterprise/consistency#vault-1-7-mitigations
// for several ways to mitigate this which are outside the scope of this code sample.
func renewToken(client *vault.Client) {
	for {
		vaultLoginResp, err := login(client)
		if err != nil {
			log.Fatalf("unable to authenticate to Vault: %v", err)
		}
		tokenErr := manageTokenLifecycle(client, vaultLoginResp)
		if tokenErr != nil {
			log.Fatalf("unable to start managing token lifecycle: %v", tokenErr)
		}
	}
}

// Starts token lifecycle management. Returns only fatal errors as errors,
// otherwise returns nil so we can attempt login again.
func manageTokenLifecycle(client *vault.Client, token *vault.Secret) error {
	renew := token.Auth.Renewable // You may notice a different top-level field called Renewable. That one is used for dynamic secrets renewal, not token renewal.
	if !renew {
		log.Printf("Token is not configured to be renewable. Re-attempting login.")
		return nil
	}

	watcher, err := client.NewLifetimeWatcher(&vault.LifetimeWatcherInput{
		Secret:    token,
		Increment: 3600, // Learn more about this optional value in https://developer.hashicorp.com/vault/docs/concepts/lease#lease-durations-and-renewal
	})
	if err != nil {
		return fmt.Errorf("unable to initialize new lifetime watcher for renewing auth token: %w", err)
	}

	go watcher.Start()
	defer watcher.Stop()

	for {
		select {
		// `DoneCh` will return if renewal fails, or if the remaining lease
		// duration is under a built-in threshold and either renewing is not
		// extending it or renewing is disabled. In any case, the caller
		// needs to attempt to log in again.
		case err := <-watcher.DoneCh():
			if err != nil {
				log.Printf("Failed to renew token: %v. Re-attempting login.", err)
				return nil
			}
			// This occurs once the token has reached max TTL.
			log.Printf("Token can no longer be renewed. Re-attempting login.")
			return nil

		// Successfully completed renewal
		case renewal := <-watcher.RenewCh():
			log.Printf("Successfully renewed: %#v", renewal)
		}
	}
}

func login(client *vault.Client) (*vault.Secret, error) {
	// WARNING: A plaintext password like this is obviously insecure.
	// See the hashicorp/vault-examples repo for full examples of how to securely
	// log in to Vault using various auth methods. This function is just
	// demonstrating the basic idea that a *vault.Secret is returned by
	// the login call.
	userpassAuth, err := auth.NewUserpassAuth("my-user", &auth.Password{FromString: "my-password"})
	if err != nil {
		return nil, fmt.Errorf("unable to initialize userpass auth method: %w", err)
	}

	authInfo, err := client.Auth().Login(context.TODO(), userpassAuth)
	if err != nil {
		return nil, fmt.Errorf("unable to login to userpass auth method: %w", err)
	}
	if authInfo == nil {
		return nil, fmt.Errorf("no auth info was returned after login")
	}

	return authInfo, nil
}
```

</CodeBlockConfig>

</CodeTabs>

layout  docs page title  Authentication description       Before performing any operation with Vault  the connecting client must be   authenticated         Authentication  Authentication in Vault is the process by which user or machine supplied information is verified against an internal or external system  Vault supports multiple  auth methods   vault docs auth  including GitHub  LDAP  AppRole  and more  Each auth method has a specific use case   Before a client can interact with Vault  it must  authenticate  against an auth method  Upon authentication  a token is generated  This token is conceptually similar to a session ID on a website  The token may have attached policy  which is mapped at authentication time  This process is described in detail in the  policies concepts   vault docs concepts policies  documentation      auth methods  Vault supports a number of auth methods  Some backends are targeted toward users while others are targeted toward machines  Most authentication backends must be enabled before use  To enable an auth method      shell session   vault auth enable userpass  path my auth      This enables the  userpass  auth method at the path  my auth   This authentication will be accessible at the path  my auth   Often you will see authentications at the same path as their name  but this is not a requirement   To learn more about this authentication  use the built in  path help  command      shell session   vault path help auth my auth            Vault supports multiple auth methods simultaneously  and you can even mount the same type of auth method at different paths  Only one authentication is required to gain access to Vault  and it is not currently possible to force a user through multiple auth methods to gain access  although some backends do support MFA      Tokens  There is an  entire page dedicated to tokens   vault docs concepts tokens   but it is important to understand that authentication works by verifying your identity and then generating a token to associate with that identity   For example  even though you may authenticate using something like GitHub  Vault generates a unique access token for you to use for future requests  The CLI automatically attaches this token to requests  but if you re using the API you ll have to do this manually   This token given for authentication with any backend can also be used with the full set of token commands  such as creating new sub tokens  revoking tokens  and renewing tokens  This is all covered on the  token concepts page   vault docs concepts tokens       Authenticating      Via the CLI  To authenticate with the CLI   vault login  is used  This supports many of the built in auth methods  For example  with GitHub      shell session   vault login  method github token  token           After authenticating  you will be logged in  The CLI command will also output your raw token  This token is used for revocation and renewal  As the user logging in  the primary use case of the token is renewal  covered below in the  Auth Leases  section   To determine what variables are needed for an auth method  supply the   method  flag without any additional arguments and help will be shown   If you re using a method that isn t supported via the CLI  then the API must be used       Via the API  API authentication is generally used for machine authentication  Each auth method implements its own login endpoint  Use the  vault path help  mechanism to find the proper endpoint   For example  the GitHub login endpoint is located at  auth github login   And to determine the arguments needed   vault path help auth github login  can be used      Auth leases  Just like secrets  identities have  leases   vault docs concepts lease  associated with them  This means that you must reauthenticate after the given lease period to continue accessing Vault   To set the lease associated with an identity  reference the help for the specific auth method in use  It is specific to each backend how leasing is implemented   And just like secrets  identities can be renewed without having to completely reauthenticate  Just use  vault token renew  token   with the leased token associated with your identity to renew it      Code example  The following code snippet demonstrates how to renew auth tokens    CodeTabs heading  token renewal example     CodeBlockConfig lineNumbers      go package main  import     context    fmt    log    vault  github com hashicorp vault api   auth  github com hashicorp vault api auth userpass        Once you ve set the token for your Vault client  you will need to    periodically renew its lease        A function like this should be run as a goroutine to avoid blocking        Production applications may also wish to be more tolerant of failures and    retry rather than exiting        Additionally  enterprise Vault users should be aware that due to eventual    consistency  the API may return unexpected errors when running Vault with    performance standbys or performance replication  despite the client having    a freshly renewed token  See https   developer hashicorp com vault docs enterprise consistency vault 1 7 mitigations    for several ways to mitigate this which are outside the scope of this code sample  func renewToken client  vault Client     for     vaultLoginResp  err    login client    if err    nil      log Fatalf  unable to authenticate to Vault   v   err        tokenErr    manageTokenLifecycle client  vaultLoginResp    if tokenErr    nil      log Fatalf  unable to start managing token lifecycle   v   tokenErr               Starts token lifecycle management  Returns only fatal errors as errors     otherwise returns nil so we can attempt login again  func manageTokenLifecycle client  vault Client  token  vault Secret  error    renew    token Auth Renewable    You may notice a different top level field called Renewable  That one is used for dynamic secrets renewal  not token renewal   if  renew     log Printf  Token is not configured to be renewable  Re attempting login      return nil      watcher  err    client NewLifetimeWatcher  vault LifetimeWatcherInput    Secret     token    Increment  3600     Learn more about this optional value in https   developer hashicorp com vault docs concepts lease lease durations and renewal      if err    nil     return fmt Errorf  unable to initialize new lifetime watcher for renewing auth token   w   err       go watcher Start    defer watcher Stop     for     select         DoneCh  will return if renewal fails  or if the remaining lease      duration is under a built in threshold and either renewing is not      extending it or renewing is disabled  In any case  the caller      needs to attempt to log in again    case err      watcher DoneCh       if err    nil       log Printf  Failed to renew token   v  Re attempting login    err      return nil            This occurs once the token has reached max TTL     log Printf  Token can no longer be renewed  Re attempting login       return nil       Successfully completed renewal   case renewal      watcher RenewCh       log Printf  Successfully renewed    v   renewal            func login client  vault Client    vault Secret  error        WARNING  A plaintext password like this is obviously insecure      See the hashicorp vault examples repo for full examples of how to securely     log in to Vault using various auth methods  This function is just     demonstrating the basic idea that a  vault Secret is returned by     the login call   userpassAuth  err    auth NewUserpassAuth  my user    auth Password FromString   my password     if err    nil     return nil  fmt Errorf  unable to initialize userpass auth method   w   err       authInfo  err    client Auth   Login context TODO    userpassAuth   if err    nil     return nil  fmt Errorf  unable to login to userpass auth method   w   err      if authInfo    nil     return nil  fmt Errorf  no auth info was returned after login        return authInfo  nil          CodeBlockConfig     CodeTabs