0
0
ElasticsearchHow-ToBeginner · 3 min read

How to Use API Key in Elasticsearch for Secure Access

To use an API key in Elasticsearch, include it in the Authorization header as ApiKey <encoded_key> when making HTTP requests. You create the API key via Elasticsearch's security API, then use the generated key to authenticate your queries securely.
📐

Syntax

Using an API key in Elasticsearch requires adding an Authorization header to your HTTP request. The header value must be ApiKey <base64_encoded_key>, where <base64_encoded_key> is the API key string provided by Elasticsearch.

The API key is created by calling the _security/api_key endpoint with your credentials. Once created, you use the key in requests to authenticate without username and password.

http
Authorization: ApiKey <base64_encoded_api_key>
💻

Example

This example shows how to create an API key and then use it to authenticate a search request in Elasticsearch.

json
POST /_security/api_key
{
  "name": "my-api-key",
  "role_descriptors": {
    "my-role": {
      "cluster": ["all"],
      "index": [
        {
          "names": ["*"],
          "privileges": ["read"]
        }
      ]
    }
  }
}

# Response example:
{
  "id": "api_key_id",
  "name": "my-api-key",
  "api_key": "Vua1bG9uZ2tleQ=="
}

# Use the API key in a request header:
GET /_search
Authorization: ApiKey Vua1bG9uZ2tleQ==
Output
{ "id": "api_key_id", "name": "my-api-key", "api_key": "Vua1bG9uZ2tleQ==" } { "took": 10, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": {"value": 100, "relation": "eq"}, "max_score": 1.0, "hits": [] } }
⚠️

Common Pitfalls

  • Not encoding the API key properly in Base64 before using it in the Authorization header.
  • Using the API key string directly without the ApiKey prefix in the header.
  • Creating API keys without proper roles or privileges, causing authorization failures.
  • Forgetting to enable Elasticsearch security features, which are required for API key usage.
http
Wrong:
Authorization: Vua1bG9uZ2tleQ==

Right:
Authorization: ApiKey Vua1bG9uZ2tleQ==
📊

Quick Reference

StepDescriptionExample
1Create API key with rolesPOST /_security/api_key {"name":"key1","role_descriptors":{...}}
2Receive API key string{"api_key":"base64string"}
3Use API key in headerAuthorization: ApiKey base64string
4Make authenticated requestsGET /_search with header

Key Takeaways

Always include the API key in the Authorization header prefixed with 'ApiKey '.
Create API keys with appropriate roles to control access.
Encode the API key properly in Base64 before use.
Elasticsearch security must be enabled to use API keys.
Use API keys to avoid sending username and password in requests.