Spring Data ElasticSearch with Basic Auth

Upasana | July 25, 2020 | 1 min read | 0 views

In this article we will configure Spring Data Elastic Search RestHighLevelClient using SSL and Basic Authentication. We will be using Spring Boot 2.2.6.RELEASE which has compatibility with Elastic Search 6.8 and above for this article.

Maven Setup

We can use either maven or gradle to configure Spring data elasticsearch.

Maven setup
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

Spring Configuration

We will be creating a Bean for RestHighLevelClient with configuration for SSL and Basic Auth.

    host: localhost
    port: 9200
    username: <username>
    password: <password>
Elastic Search Bean Configuration
@EnableElasticsearchRepositories(basePackages = {"com.example.search"})
public class ESConfig extends AbstractElasticsearchConfiguration {

    private String host;

    private int port;

    private String username;

    private String password;

    public RestHighLevelClient elasticsearchClient() {
        ClientConfiguration.MaybeSecureClientConfigurationBuilder builder = ClientConfiguration.builder()
                .connectedTo(host+ ":" + port)
                .usingSsl() (1)
                .withBasicAuth(username, password); (2)
        final ClientConfiguration clientConfiguration = builder.build();
        return RestClients.create(clientConfiguration).rest();
1 Using SSL for Secure HTTPS configuration
2 Using Basic Auth for authentication

Once this configuration is created, Spring will automatically use this RestHighLevelClient for creating instance of Bean ElasticsearchOperations.

A simple example using the ElasticsearchOperations is shown below:

public class ElasticSearchClient {

    private ElasticsearchOperations elasticsearchOperations;

    public void useTemplate() {


That’s all.

Top articles in this category:
  1. Spring RestTemplate Basic Authentication
  2. Elasticsearch with Spring Boot + Spring Data
  3. Basic Auth Security in Spring Boot 2
  4. Spring Boot WebClient Basic Authentication
  5. Prevent Lost Updates in Database Transaction using Spring Hibernate
  6. Redis rate limiter in Spring Boot
  7. Custom TTL for Spring data Redis Cache

Recommended books for interview preparation:

Find more on this topic: