---
type: api
title: Create a cross-cluster API key
description: Create an API key of the `cross_cluster` type for the API key based remote cluster access.
url: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/operation/operation-security-create-cross-cluster-api-key
resource: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/operation/operation-security-create-cross-cluster-api-key
products:
  - Elasticsearch
---

# Create a cross-cluster API key

Availability:

## Paths

- `POST` `/_security/cross_cluster/api_key`

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

## Description

Create an API key of the `cross_cluster` type for the API key based remote cluster access.
A `cross_cluster` API key cannot be used to authenticate through the REST interface.

IMPORTANT: To authenticate this request you must use a credential that is not an API key. Even if you use an API key that has the required privilege, the API returns an error.

Cross-cluster API keys are created by the Elasticsearch API key service, which is automatically enabled.

NOTE: Unlike REST API keys, a cross-cluster API key does not capture permissions of the authenticated user. The API key’s effective permission is exactly as specified with the `access` property.

A successful request 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.

Cross-cluster API keys can only be updated with the update cross-cluster API key API.
Attempting to update them with the update REST API key API or the bulk update REST API keys API will result in an error.

## Required authorization

* Cluster privileges: `manage_security`

[Read the reference documentation](https://www.elastic.co/guide/en/elasticsearch/reference/8.19/remote-clusters-api-key.html)

## Request Body

`application/json`

- `access` ({} Access) — required
  The access to be granted to this API key.
The access is composed of permissions for cross-cluster search and cross-cluster replication.
At least one of them must be specified.

NOTE: No explicit privileges should be specified for either search or replication access.
The creation process automatically converts the access specification to a role descriptor which has relevant privileges assigned accordingly.
  - `replication` ([] ReplicationAccess) — optional
    A list of indices permission entries for cross-cluster replication.
    - `names` (union IndexName | [] IndexName) — required
      A list of indices (or index name patterns) to which the permissions in this entry apply.
    - `allow_restricted_indices` (boolean · default: false) — optional
      This needs to be set to true if the patterns in the names field should cover system indices.
  - `search` ([] SearchAccess) — optional
    A list of indices permission entries for cross-cluster search.
    - `field_security` ({} FieldSecurity) — optional
      The document fields that the owners of the role have read access to.
      - `except` (string Fields) — optional
      - `grant` (string Fields) — optional
    - `names` (union IndexName | [] IndexName) — required
      A list of indices (or index name patterns) to which the permissions in this entry apply.
    - `query` (IndicesPrivilegesQuery) — optional
      A search query that defines the documents the owners of the role have access to. A document within the specified indices must match this query for it to be accessible by the owners of the role.
    - `allow_restricted_indices` (boolean · default: false) — optional
      Set to `true` if using wildcard or regular expressions for patterns that cover restricted indices. Implicitly, restricted indices have limited privileges that can cause pattern tests to fail. If restricted indices are explicitly included in the `names` list, Elasticsearch checks privileges against these indices regardless of the value set for `allow_restricted_indices`.
- `expiration` (string Duration) — optional
  Expiration time for the API key.
By default, API keys never expire.
- `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.
- `name` (string Name) — required
  Specifies the name for this API key.

## Response

`application/json`

- `api_key` (string)
  Generated API key.
- `expiration` (DurationValueUnitMillis)
  Expiration in milliseconds for the API key.
- `id` (string Id)
  Unique ID for this API key.
- `name` (string Name)
  Specifies the name for this API key.
- `encoded` (string)
  API key credentials which is the base64-encoding of
the UTF-8 representation of `id` and `api_key` joined
by a colon (`:`).
## Code Examples

#### Console

```console
POST /_security/cross_cluster/api_key
{
  "name": "my-cross-cluster-api-key",
  "expiration": "1d",   
  "access": {
    "search": [  
      {
        "names": ["logs*"]
      }
    ],
    "replication": [  
      {
        "names": ["archive*"]
      }
    ]
  },
  "metadata": {
    "description": "phase one",
    "environment": {
      "level": 1,
      "trusted": true,
      "tags": ["dev", "staging"]
    }
  }
}
```

#### JavaScript

```javascript
const response = await client.security.createCrossClusterApiKey({
  name: "my-cross-cluster-api-key",
  expiration: "1d",
  access: {
    search: [
      {
        names: ["logs*"],
      },
    ],
    replication: [
      {
        names: ["archive*"],
      },
    ],
  },
  metadata: {
    description: "phase one",
    environment: {
      level: 1,
      trusted: true,
      tags: ["dev", "staging"],
    },
  },
});
```

#### Python

```python
resp = client.security.create_cross_cluster_api_key(
    name="my-cross-cluster-api-key",
    expiration="1d",
    access={
        "search": [
            {
                "names": [
                    "logs*"
                ]
            }
        ],
        "replication": [
            {
                "names": [
                    "archive*"
                ]
            }
        ]
    },
    metadata={
        "description": "phase one",
        "environment": {
            "level": 1,
            "trusted": True,
            "tags": [
                "dev",
                "staging"
            ]
        }
    },
)
```

#### curl

```curl
curl -X POST "$ELASTICSEARCH_URL/_security/cross_cluster/api_key" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-cross-cluster-api-key",
    "expiration": "1d",
    "access": {
      "search": [
        {
          "names": [
            "logs*"
          ]
        }
      ],
      "replication": [
        {
          "names": [
            "archive*"
          ]
        }
      ]
    },
    "metadata": {
      "description": "phase one",
      "environment": {
        "level": 1,
        "trusted": true,
        "tags": [
          "dev",
          "staging"
        ]
      }
    }
  }'
```

#### Java

```java
client.security().createCrossClusterApiKey(c -> c
    .access(a -> a
        .replication(r -> r
            .names("archive*")
        )
        .search(s -> s
            .names("logs*")
        )
    )
    .expiration(e -> e
        .time("1d")
    )
    .metadata(Map.of("environment", JsonData.fromJson("{\"level\":1,\"trusted\":true,\"tags\":[\"dev\",\"staging\"]}"),"description", JsonData.fromJson("\"phase one\"")))
    .name("my-cross-cluster-api-key")
);
```

#### C#

```c#
var response = await client.Security
    .CreateCrossClusterApiKeyAsync(d1 => d1
        .Access(d2 => d2
            .Replication(d3 => d3
                .Names(["archive*"])
            )
            .Search(d3 => d3
                .Names(["logs*"])
            )
        )
        .Expiration("1d")
        .Metadata(new Dictionary<string, object>()
        {
            { "description", "phase one" },
            { "environment", JsonSerializer.Deserialize<JsonElement>("""
            {
              "level": 1,
              "trusted": true,
              "tags": [
                "dev",
                "staging"
              ]
            }
            """) }
        })
        .Name("my-cross-cluster-api-key")
    );
```

#### PHP

```php
$resp = $client->security()->createCrossClusterApiKey([
    "body" => [
        "name" => "my-cross-cluster-api-key",
        "expiration" => "1d",
        "access" => [
            "search" => array(
                [
                    "names" => array(
                        "logs*",
                    ),
                ],
            ),
            "replication" => array(
                [
                    "names" => array(
                        "archive*",
                    ),
                ],
            ),
        ],
        "metadata" => [
            "description" => "phase one",
            "environment" => [
                "level" => 1,
                "trusted" => true,
                "tags" => array(
                    "dev",
                    "staging",
                ),
            ],
        ],
    ],
]);
```

#### Ruby

```ruby
response = client.security.create_cross_cluster_api_key(
  body: {
    "name": "my-cross-cluster-api-key",
    "expiration": "1d",
    "access": {
      "search": [
        {
          "names": [
            "logs*"
          ]
        }
      ],
      "replication": [
        {
          "names": [
            "archive*"
          ]
        }
      ]
    },
    "metadata": {
      "description": "phase one",
      "environment": {
        "level": 1,
        "trusted": true,
        "tags": [
          "dev",
          "staging"
        ]
      }
    }
  }
)
```

## Response Examples

#### Create cross cluster api key response example1

A successful response from `POST /_security/service/elastic/fleet-server/credential/token`.

```json
{
  "created": true,
  "token": {
    "name": "Jk5J1HgBuyBK5TpDrdo4",
    "value": "AAEAAWVsYXN0aWM...vZmxlZXQtc2VydmVyL3Rva2VuMTo3TFdaSDZ"
  }
}
```

