How to Set Up Authentication in Elasticsearch Quickly
To set up authentication in
Elasticsearch, enable the built-in security features by configuring xpack.security.enabled: true in the elasticsearch.yml file. Then, create users and assign roles using the elasticsearch-users tool or the Security API to control access.Syntax
Authentication setup in Elasticsearch mainly involves enabling security and managing users and roles.
xpack.security.enabled: true— turns on security features including authentication.elasticsearch-userscommand — used to add, delete, or modify users.- Security API endpoints — allow programmatic user and role management.
bash / json
## Enable security in elasticsearch.yml xpack.security.enabled: true ## Add a user with the command line tool elasticsearch-users useradd <username> -p <password> -r <role> ## Example API call to create a user PUT /_security/user/<username> { "password" : "<password>", "roles" : ["<role>"] }
Example
This example shows how to enable authentication, create a user, and test login.
bash
# Step 1: Enable security in elasticsearch.yml xpack.security.enabled: true # Step 2: Restart Elasticsearch to apply changes # Step 3: Create a user with the built-in tool elasticsearch-users useradd alice -p alicepassword -r superuser # Step 4: Test authentication with curl curl -u alice:alicepassword -X GET "localhost:9200/_security/_authenticate"
Output
{
"username" : "alice",
"roles" : [ "superuser" ],
"full_name" : null,
"email" : null,
"metadata" : { },
"enabled" : true
}
Common Pitfalls
- Forgetting to restart Elasticsearch after enabling
xpack.security.enabledcauses authentication to not work. - Not setting passwords for built-in users leads to login failures.
- Using the wrong roles or missing role assignments prevents access to APIs.
- Trying to use authentication without a license that supports security features (for older versions).
yaml
# Wrong: Not enabling security # elasticsearch.yml xpack.security.enabled: false # Right: Enable security xpack.security.enabled: true
Quick Reference
| Step | Command / Setting | Description |
|---|---|---|
| 1 | xpack.security.enabled: true | Enable security features in elasticsearch.yml |
| 2 | elasticsearch-users useradd | Create a user with password and role |
| 3 | curl -u | Test authentication |
| 4 | Assign roles carefully | Ensure users have correct permissions |
Key Takeaways
Enable security by setting xpack.security.enabled to true in elasticsearch.yml.
Create users with passwords and assign roles using elasticsearch-users or Security API.
Restart Elasticsearch after configuration changes to activate authentication.
Test authentication with the _security/_authenticate API endpoint.
Avoid common mistakes like missing passwords or roles to ensure access.