---
type: api
title: Grant an API key
description: Create an API key on behalf of another user.
url: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/operation/operation-security-grant-api-key
resource: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/operation/operation-security-grant-api-key
products:
  - Elasticsearch
---

# Grant an API key

Availability: 7.9+

## Paths

- `POST` `/_security/api_key/grant`

- [Api key auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#apikeyauth)
- [Basic auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#basicauth)
- [Bearer auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#bearerauth)

## Description

Create an API key on behalf of another user.
This API is similar to the create API keys API, however it creates the API key for a user that is different than the user that runs the API.
The caller must have authentication credentials for the user on whose behalf the API key will be created.
It is not possible to use this API to create an API key without that user's credentials.
The supported user authentication credential types are:

* username and password
* Elasticsearch access tokens
* JWTs

The user, for whom the authentication credentials is provided, can optionally "run as" (impersonate) another user.
In this case, the API key will be created on behalf of the impersonated user.

This API is intended be used by applications that need to create and manage API keys for end users, but cannot guarantee that those users have permission to create API keys on their own behalf.
The API keys are created by the Elasticsearch API key service, which is automatically enabled.

A successful grant API key API call returns a JSON structure that contains the API key, its unique id, and its name.
If applicable, it also returns expiration information for the API key in milliseconds.

By default, API keys never expire. You can specify expiration information when you create the API keys.

## Required authorization

* Cluster privileges: `grant_api_key`

## Query String Parameters

- `refresh` (enum Refresh · default: false)
  If 'true', Elasticsearch refreshes the affected shards to make this operation
visible to search.
If 'wait_for', it waits for a refresh to make this operation visible to search.
If 'false', nothing is done with refreshes.
  Values: `true`, `false`, `wait_for`

## Request Body

`application/json`

- `api_key` ({} GrantApiKey) — required
  The API key.
  - `name` (string Name) — required
  - `expiration` (string) — optional
    Expiration time for the API key. By default, API keys never expire.
  - `role_descriptors` (union oneOf) — optional
    The role descriptors for this API key.
When it is not specified or is an empty array, the API key has a point in time snapshot of permissions of the specified user or access token.
If you supply role descriptors, the resultant permissions are an intersection of API keys permissions and the permissions of the user or access token.
    `map string to RoleDescriptor` or `[] map string to RoleDescriptor`
  - `metadata` (Metadata) — optional
    Arbitrary metadata that you want to associate with the API key.
It supports nested data structure.
Within the `metadata` object, keys beginning with `_` are reserved for system usage.
- `grant_type` (enum ApiKeyGrantType) — required
  The type of grant. Supported grant types are: `access_token`, `password`.
  Values: `access_token`, `password`
- `access_token` (string) — optional
  The user's access token.
If you specify the `access_token` grant type, this parameter is required.
It is not valid with other grant types.
- `username` (string) — optional
  The user name that identifies the user.
If you specify the `password` grant type, this parameter is required.
It is not valid with other grant types.
- `password` (string) — optional
  The user's password.
If you specify the `password` grant type, this parameter is required.
It is not valid with other grant types.
- `run_as` (string) — optional
  The name of the user to be impersonated.

## Response

`application/json`

- `api_key` (string)
- `id` (string Id)
- `name` (string Name)
- `expiration` (EpochTimeUnitMillis)
- `encoded` (string)
## Code Examples

#### Console

```console
POST /_security/api_key/grant
{
  "grant_type": "password",
  "username" : "test_admin",
  "password" : "x-pack-test-password",
  "api_key" : {
    "name": "my-api-key",
    "expiration": "1d",
    "role_descriptors": {
      "role-a": {
        "cluster": ["all"],
        "indices": [
          {
          "names": ["index-a*"],
          "privileges": ["read"]
          }
        ]
      },
      "role-b": {
        "cluster": ["all"],
        "indices": [
          {
          "names": ["index-b*"],
          "privileges": ["all"]
          }
        ]
      }
    },
    "metadata": {
      "application": "my-application",
      "environment": {
        "level": 1,
        "trusted": true,
        "tags": ["dev", "staging"]
      }
    }
  }
}
```

#### JavaScript

```javascript
const response = await client.security.grantApiKey({
  grant_type: "password",
  username: "test_admin",
  password: "x-pack-test-password",
  api_key: {
    name: "my-api-key",
    expiration: "1d",
    role_descriptors: {
      "role-a": {
        cluster: ["all"],
        indices: [
          {
            names: ["index-a*"],
            privileges: ["read"],
          },
        ],
      },
      "role-b": {
        cluster: ["all"],
        indices: [
          {
            names: ["index-b*"],
            privileges: ["all"],
          },
        ],
      },
    },
    metadata: {
      application: "my-application",
      environment: {
        level: 1,
        trusted: true,
        tags: ["dev", "staging"],
      },
    },
  },
});
```

#### Python

```python
resp = client.security.grant_api_key(
    grant_type="password",
    username="test_admin",
    password="x-pack-test-password",
    api_key={
        "name": "my-api-key",
        "expiration": "1d",
        "role_descriptors": {
            "role-a": {
                "cluster": [
                    "all"
                ],
                "indices": [
                    {
                        "names": [
                            "index-a*"
                        ],
                        "privileges": [
                            "read"
                        ]
                    }
                ]
            },
            "role-b": {
                "cluster": [
                    "all"
                ],
                "indices": [
                    {
                        "names": [
                            "index-b*"
                        ],
                        "privileges": [
                            "all"
                        ]
                    }
                ]
            }
        },
        "metadata": {
            "application": "my-application",
            "environment": {
                "level": 1,
                "trusted": True,
                "tags": [
                    "dev",
                    "staging"
                ]
            }
        }
    },
)
```

#### curl

```curl
curl -X POST "$ELASTICSEARCH_URL/_security/api_key/grant" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "grant_type": "password",
    "username": "test_admin",
    "password": "x-pack-test-password",
    "api_key": {
      "name": "my-api-key",
      "expiration": "1d",
      "role_descriptors": {
        "role-a": {
          "cluster": [
            "all"
          ],
          "indices": [
            {
              "names": [
                "index-a*"
              ],
              "privileges": [
                "read"
              ]
            }
          ]
        },
        "role-b": {
          "cluster": [
            "all"
          ],
          "indices": [
            {
              "names": [
                "index-b*"
              ],
              "privileges": [
                "all"
              ]
            }
          ]
        }
      },
      "metadata": {
        "application": "my-application",
        "environment": {
          "level": 1,
          "trusted": true,
          "tags": [
            "dev",
            "staging"
          ]
        }
      }
    }
  }'
```

#### Java

```java
client.security().grantApiKey(g -> g
    .apiKey(a -> a
        .name("my-api-key")
        .expiration(e -> e
            .time("1d")
        )
        .roleDescriptors(Map.of("role-b", RoleDescriptor.roleDescriptorOf(r -> r
                .cluster("all")
                .indices(i -> i
                    .names("index-b*")
                    .privileges("all")
                )
            ),"role-a", RoleDescriptor.roleDescriptorOf(r -> r
                .cluster("all")
                .indices(i -> i
                    .names("index-a*")
                    .privileges("read")
                )
            )))
        .metadata(Map.of("environment", JsonData.fromJson("""
{"level":1,"trusted":true,"tags":["dev","staging"]}
"""),"application", JsonData.fromJson("\"my-application\"")))
    )
    .grantType(ApiKeyGrantType.Password)
    .password("x-pack-test-password")
    .username("test_admin")
);
```

#### C#

```c#
var response = await client.Security
    .GrantApiKeyAsync(d1 => d1
        .ApiKey(d2 => d2
            .Expiration("1d")
            .Metadata(new Dictionary<string, object>()
            {
                { "application", "my-application" },
                { "environment", JsonSerializer.Deserialize<JsonElement>("""
                {
                  "level": 1,
                  "trusted": true,
                  "tags": [
                    "dev",
                    "staging"
                  ]
                }
                """) }
            })
            .Name("my-api-key")
            .RoleDescriptors([new Dictionary<string, RoleDescriptor>()
            {
                { "role-a", new()
                {
                    Cluster = [ClusterPrivilege.All],
                    Indices = [new()
                    {
                        Names = ["index-a*"],
                        Privileges = [IndexPrivilege.Read]
                    }]
                } },
                { "role-b", new()
                {
                    Cluster = [ClusterPrivilege.All],
                    Indices = [new()
                    {
                        Names = ["index-b*"],
                        Privileges = [IndexPrivilege.All]
                    }]
                } }
            }])
        )
        .GrantType(ApiKeyGrantType.Password)
        .Password("x-pack-test-password")
        .Username("test_admin")
    );
```

#### PHP

```php
$resp = $client->security()->grantApiKey([
    "body" => [
        "grant_type" => "password",
        "username" => "test_admin",
        "password" => "x-pack-test-password",
        "api_key" => [
            "name" => "my-api-key",
            "expiration" => "1d",
            "role_descriptors" => [
                "role-a" => [
                    "cluster" => array(
                        "all",
                    ),
                    "indices" => array(
                        [
                            "names" => array(
                                "index-a*",
                            ),
                            "privileges" => array(
                                "read",
                            ),
                        ],
                    ),
                ],
                "role-b" => [
                    "cluster" => array(
                        "all",
                    ),
                    "indices" => array(
                        [
                            "names" => array(
                                "index-b*",
                            ),
                            "privileges" => array(
                                "all",
                            ),
                        ],
                    ),
                ],
            ],
            "metadata" => [
                "application" => "my-application",
                "environment" => [
                    "level" => 1,
                    "trusted" => true,
                    "tags" => array(
                        "dev",
                        "staging",
                    ),
                ],
            ],
        ],
    ],
]);
```

#### Ruby

```ruby
response = client.security.grant_api_key(
  body: {
    "grant_type": "password",
    "username": "test_admin",
    "password": "x-pack-test-password",
    "api_key": {
      "name": "my-api-key",
      "expiration": "1d",
      "role_descriptors": {
        "role-a": {
          "cluster": [
            "all"
          ],
          "indices": [
            {
              "names": [
                "index-a*"
              ],
              "privileges": [
                "read"
              ]
            }
          ]
        },
        "role-b": {
          "cluster": [
            "all"
          ],
          "indices": [
            {
              "names": [
                "index-b*"
              ],
              "privileges": [
                "all"
              ]
            }
          ]
        }
      },
      "metadata": {
        "application": "my-application",
        "environment": {
          "level": 1,
          "trusted": true,
          "tags": [
            "dev",
            "staging"
          ]
        }
      }
    }
  }
)
```

