Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
How to Handle Authentication with Postman API Testing?
Next article icon

Elasticsearch API Authentication: How to Set Up with Examples

Last Updated : 29 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Elasticsearch is a powerful distributed search and analytics engine widely used for logging, monitoring, and data analysis. To protect your data and ensure secure access, setting up API authentication is essential.

This article will guide you through the process of configuring Elasticsearch API authentication with detailed examples and outputs. We will cover basic authentication, API keys, and role-based access control (RBAC).

Why API Authentication is Important

API authentication in Elasticsearch is crucial for several reasons:

  • Data Security: Prevent unauthorized access to your data.
  • Data Integrity: Ensure that only authenticated users can modify data.
  • Auditability: Track who accessed or modified data.
  • Compliance: Meet regulatory requirements for data protection.

Prerequisites

Before setting up API authentication, ensure you have the following:

  • Elasticsearch is installed and running.
  • Kibana is installed and running (for managing users and roles via the UI).
  • Basic knowledge of Elasticsearch and its REST API.

Enabling Security Features

By default, Elasticsearch security features are disabled. To enable them, you need to configure Elasticsearch and restart it.

Step 1: Update the Configuration

Open the elasticsearch.yml configuration file and add the following settings:

xpack.security.enabled: true

Step 2: Generate Certificates

Elasticsearch requires transport and HTTP layer encryption. Use the elasticsearch-certutil tool to generate the necessary certificates.

bin/elasticsearch-certutil ca
bin/elasticsearch-certutil cert --ca elastic-stack-ca.p12

Follow the prompts to generate the certificates.

Step 3: Configure the Keystore

Add the generated certificates to the Elasticsearch keystore:

bin/elasticsearch-keystore add xpack.security.transport.ssl.keystore.secure_password
bin/elasticsearch-keystore add xpack.security.transport.ssl.truststore.secure_password

Step 4: Restart Elasticsearch

Restart Elasticsearch to apply the changes.

bin/elasticsearch

Setting Up Basic Authentication

Basic authentication uses usernames and passwords to control access to the Elasticsearch API.

Step 1: Create a User

You can create users using the Kibana UI or the Elasticsearch REST API.

Using Kibana

  • Open Kibana and go to Management > Security > Users.
  • Click Create user.
  • Fill in the username, password, and assign roles (e.g., superuser).

Using the REST API

Alternatively, you can create a user using the REST API:

curl -X POST "localhost:9200/_security/user/my_user" -H 'Content-Type: application/json' -d'
{
"password" : "mypassword",
"roles" : [ "superuser" ],
"full_name" : "John Doe",
"email" : "[email protected]"
}'

Step 2: Authenticate API Requests

To authenticate API requests, include the username and password in the request header.

Example: Indexing a Document

curl -u my_user:mypassword -X POST "localhost:9200/myindex/_doc/1" -H 'Content-Type: application/json' -d'
{
"name": "John Doe",
"age": 30,
"city": "New York"
}'

Output

The response indicates that the document is indexed successfully:

{
"_index": "myindex",
"_id": "1",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}

Setting Up API Key Authentication

API keys provide an alternative method for authenticating API requests without using usernames and passwords.

Step 1: Create an API Key

Create an API key using the Elasticsearch REST API:

curl -u my_user:mypassword -X POST "localhost:9200/_security/api_key" -H 'Content-Type: application/json' -d'
{
"name": "my_api_key",
"role_descriptors": {
"my_role": {
"cluster": ["all"],
"index": [
{
"names": ["*"],
"privileges": ["all"]
}
]
}
}
}'

Step 2: Authenticate API Requests with the API Key

Include the API key in the request header.

Example: Indexing a Document

curl -H "Authorization: ApiKey <base64-encoded-api-key>" -X POST "localhost:9200/myindex/_doc/1" -H 'Content-Type: application/json' -d'
{
"name": "Jane Doe",
"age": 25,
"city": "San Francisco"
}'

To base64-encode the API key, use the following command (replace id:key with your actual API key):

echo -n "id:key" | base64

Output

The response indicates that the document is indexed successfully:

{
"_index": "myindex",
"_id": "1",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}

Role-Based Access Control (RBAC)

RBAC allows you to define roles with specific permissions and assign these roles to users and API keys.

Step 1: Define Roles

Create roles that define specific permissions using the Kibana UI or the REST API.

Using Kibana

  • Open Kibana and go to Management > Security > Roles.
  • Click Create role.
  • Define the role name and permissions (e.g., read access to specific indices).

Using the REST API

Alternatively, create a role using the REST API:

curl -u my_user:mypassword -X PUT "localhost:9200/_security/role/my_role" -H 'Content-Type: application/json' -d'
{
"cluster": ["all"],
"indices": [
{
"names": ["myindex"],
"privileges": ["read"]
}
]
}'

Step 2: Assign Roles to Users

Assign the created role to a user using the Kibana UI or the REST API.

Using Kibana

  • Open Kibana and go to Management > Security > Users.
  • Edit the user and assign the role.

Using the REST API

Assign a role to a user using the REST API:

curl -u my_user:mypassword -X POST "localhost:9200/_security/user/my_user/_roles" -H 'Content-Type: application/json' -d'
{
"roles": ["my_role"]
}'

Step 3: Authenticate API Requests

Authenticated API requests will now have access based on the assigned roles.

Example: Querying an Index with Role-Based Permissions

curl -u my_user:mypassword -X GET "localhost:9200/myindex/_search" -H 'Content-Type: application/json' -d'
{
"query": {
"match_all": {}
}
}'

Output

The response will include documents from the myindex index:

{
"took": 10,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.0,
"hits": [
{
"_index": "myindex",
"_id": "1",
"_score": 1.0,
"_source": {
"name": "Jane Doe",
"age": 25,
"city": "San Francisco"
}
}
]
}
}

Conclusion

Setting up API authentication in Elasticsearch is essential for securing access to your data and ensuring that only authorized users can interact with your Elasticsearch clusters. This article covered the basics of enabling security features, setting up basic authentication, using API keys, and implementing role-based access control (RBAC).

By following these steps, you can enhance the security of your Elasticsearch deployment and provide controlled access to your data, helping to maintain data integrity and comply with security requirements. Experiment with different configurations and techniques to tailor the authentication setup to your specific needs and environment.


Next Article
How to Handle Authentication with Postman API Testing?

K

kumarsar29u2
Improve
Article Tags :
  • Databases
  • Elasticsearch

Similar Reads

  • How to Handle Authentication with Postman API Testing?
    Authentication is very important for securing access to resources and data. When testing APIs, handling authentication correctly is important to ensure that your tests can interact with secured endpoints effectively. Postman, a popular API testing tool, provides robust features for handling various
    4 min read
  • How to make a request using HTTP basic authentication with PHP curl?
    Making secure API requests is a common requirement in web development, and PHP provides a powerful tool for this purpose, which is cURL. The challenge is to seamlessly integrate HTTP basic authentication with PHP cURL for secure API communication. This involves not only transmitting sensitive user c
    3 min read
  • Implementing User Authentication with Next JS and Firebase
    In this article, we are going to learn how we can use Firebase with Next JS to implement user authentication. So, that user can log in using their credentials or Google account. For this project, sound knowledge of Next JS and FIrebase is required. If you are new then, don't worry every step in this
    6 min read
  • How To Implement JWT Authentication in Express App?
    Authentication is important in web apps to make sure only the right people can access certain pages or information. It helps keep user data safe and prevents unauthorized access. Implementing JSON Web Token (JWT) authentication in an Express.js application secures routes by ensuring that only authen
    6 min read
  • How to Use API Keys authentication in Postman
    Postman is an API(application programming interface) development tool that helps to build, test and modify APIs.  In this tutorial, we will see how to use API Keys authentication in Postman. The API key is a unique identifier that authenticates requests and if several users are there, their username
    2 min read
  • How to add Bearer Token authentication in Postman ?
    Postman is a crucial platform for developers, aiding in API testing, creation, and modification. APIs support various website features, such as user registration and login. For secure actions like changing passwords, Bearer Token Authentication is used. Upon login, the server issues a token, acting
    3 min read
  • GitHub Authentication with Firebase
    GitHub Authentication in Firebase allows users to sign in to our web application using their GitHub credentials. This integration uses GitHub's OAuth authentication system which provides a secure and convenient way for users to access your app. By integrating GitHub authentication, we can enhance us
    5 min read
  • How to generate API documentation using Postman?
    Postman is a popular API testing tool that is used to simplify the process of developing and testing APIs (Application Programming Interface). API acts as a bridge between two software applications which enables them to communicate and share data. In this article, you will learn how to generate API
    2 min read
  • Access a Site with Two-Factor Authentication Using Python Requests
    web security is of paramount importance, and many websites implement two-factor authentication (2FA) to enhance security. This additional layer of security ensures that even if someone obtains your password, they cannot access your account without the second form of verification, usually a code sent
    4 min read
  • How to Authenticate Git Push with Github Using a Token?
    Git is a powerful version control system used by developers to track changes in their codebase. GitHub, a platform built around Git, allows developers to collaborate on projects and manage repositories. For years, developers have been using their GitHub username and password to authenticate Git oper
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences