Grant an API key Generally available; Added in 7.9.0

POST /_security/api_key/grant

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 parameters

  • refresh string

    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 are true, false, or wait_for.

application/json

Body Required

  • api_key object Required

    The API key.

    Hide api_key attributes Show api_key attributes object
    • name string Required
    • expiration string

      Expiration time for the API key. By default, API keys never expire.

    • role_descriptors object | array[object]

      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.

      One of:
      Hide attribute Show attribute object
      • * object Additional properties
        Hide * attributes Show * attributes object
        • cluster array[string]

          A list of cluster privileges. These privileges define the cluster level actions that API keys are able to execute.

        • indices array[object]

          A list of indices permissions entries.

        • remote_indices array[object] Generally available; Added in 8.14.0

          A list of indices permissions for remote clusters.

        • remote_cluster array[object] Generally available; Added in 8.15.0

          A list of cluster permissions for remote clusters. NOTE: This is limited a subset of the cluster permissions.

        • global
        • applications array[object]

          A list of application privilege entries

        • metadata
        • run_as array[string]

          A list of users that the API keys can impersonate. NOTE: In Elastic Cloud Serverless, the run-as feature is disabled. For API compatibility, you can still specify an empty run_as field, but a non-empty list will be rejected.

        • description string

          Optional description of the role descriptor

        • restriction
        • transient_metadata object
    • metadata object

      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.

      Hide metadata attribute Show metadata attribute object
      • * object Additional properties
  • grant_type string Required

    The type of grant. Supported grant types are: access_token, password.

    Values are access_token or password.

  • access_token string

    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

    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

    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

    The name of the user to be impersonated.

Responses

  • 200 application/json
    Hide response attributes Show response attributes object
    • api_key string Required
    • id string Required
    • name string Required
    • expiration number

      Time unit for milliseconds

    • encoded string Required
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"]
      }
    }
  }
}
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"
                ]
            }
        }
    },
)
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"],
      },
    },
  },
});
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"
          ]
        }
      }
    }
  }
)
$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",
                    ),
                ],
            ],
        ],
    ],
]);
curl -X POST -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"]}}}}' "$ELASTICSEARCH_URL/_security/api_key/grant"
client.security().grantApiKey(g -> g
    .apiKey(a -> a
        .name("my-api-key")
        .expiration(e -> e
            .time("1d")
        )
        .roleDescriptors(Map.of("role-b", RoleDescriptor.of(r -> r
                .cluster("all")
                .indices(i -> i
                    .names("index-b*")
                    .privileges("all")
                )),"role-a", RoleDescriptor.of(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")
);
Request examples
Run `POST /_security/api_key/grant` to create an API key on behalf of the `test_admin` user.
{
  "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"]
      }
    }
  }
}
Run `POST /_security/api_key/grant`. The user (`test_admin`) whose credentials are provided can "run as" another user (`test_user`). The API key will be granted to the impersonated user (`test_user`).
{
  "grant_type": "password",
  "username" : "test_admin",  
  "password" : "x-pack-test-password",  
  "run_as": "test_user",  
  "api_key" : {
    "name": "another-api-key"
  }
}