<?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">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
</dependencies>
</project>
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.
Spring Configuration
We will be creating a Bean
for RestHighLevelClient with configuration for SSL and Basic Auth.
elasticsearch:
host: localhost
port: 9200
username: <username>
password: <password>
@Configuration
@EnableElasticsearchRepositories(basePackages = {"com.example.search"})
public class ESConfig extends AbstractElasticsearchConfiguration {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port:9200}")
private int port;
@Value("${elasticsearch.username}")
private String username;
@Value("${elasticsearch.password}")
private String password;
@Bean
@Override
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:
@Service
public class ElasticSearchClient {
@Qualifier("elasticsearchTemplate")
@Autowired
private ElasticsearchOperations elasticsearchOperations;
public void useTemplate() {
}
}
That’s all.
Top articles in this category:
- Spring RestTemplate Basic Authentication
- Elasticsearch with Spring Boot + Spring Data
- Basic Auth Security in Spring Boot 2
- Spring Boot WebClient Basic Authentication
- Prevent Lost Updates in Database Transaction using Spring Hibernate
- Redis rate limiter in Spring Boot
- Custom TTL for Spring data Redis Cache