Spring boot REST API Security

In this post will see how to secure the REST API using Basic Authentication with Spring security features. In this example, we will be using Spring boot to avoid basic configuration I will describe only the security part of Spring REST and how to test with Postman

Basic Authentication in REST API

Basic authentification is a standard HTTP header with the user and password encoded in base64 : Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==.The userName and password are encoded in the format username: password. This is one of the simplest technique to protect the REST resources because it does not require cookies. session identifiers or any login pages.

In case of basic authentication, the username and password is only encoded with Base64, but not encrypted or hashed in any way. Hence, it can be compromised by any man in the middle. Hence, it is always recommended to authenticate rest API calls by this header over an SSL connection.

Now we will see how to add the basic authentication to the REST API in Spring boot using the custom authentication provider

Adding maven dependencies

For rest security, we need to add the below dependencies in your pom.xml file


spring-boot-starter-security will take care of all the required dependencies related to spring security.

Now let’s add a main configuration for the Rest Security

Create Security config class inheriting the org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter

And create a CustomAuthentication class which implements the org.springframework.security.authentication.AuthenticationProvider

Override the method of public Authentication authenticate(Authentication authentication) throws AuthenticationException { }

with your authentication implementation, in this example, I added a hash map and put the default username and password in the map collection. you can get it from Database or use any 3rd party LDAP / SMAL integration

Check the code embedded in this blog

Also published on Medium.

Default image
Vignesh A Sathiyanantham
AWS Certified developer with 8 years of extensive experience working for Cloud and Datacenter solutions and leading a small team in a lean startup based on Bangalore, India

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.