Updated April 3, 2023
Definition
Spring boot basic authentication is defined as a methodology through which authentication to web services is achieved in the most basic form. In a web service, Spring Boot REST APIs might have different clients who access the same from different locations, and some of these APIs need to provide sensitive and confidential information and in such scenarios, it becomes equally important and makes itself the highest priority to secure the APIs and share the information only to the authorized set of clients. In this article, we will focus on basic authentication, but one must be mindful of other advanced authentication methodologies such as digest authentication, OAuth, and OAuth2 authentication.
What is Spring Boot Basic Authentication?
The spring boot basic authentication refers to the methodology to secure the space of APIs against any fraudulent attacks that requires user login credentials to be passed as HTTP request header which makes it ideal for authentication REST clients. In this section, we will learn about spring boot basic authentication from the angle of syntax so that while we learn about how basic authentication is performed and its working methodology, mapping back to the syntax will allow readers to look at the complete and bigger picture of the topic in the discussion of the article.
Building JAR file using Maven:
mvn clean install
Running JAR file through command line:
java -jar <Name of the JAR file>
How to perform basic authentication in Spring boot?
By now we know that basic authentication is a standardized methodology which is a standard HTTP header where the user and password are encoded in a base64 format and the encoded format is username: password. The reason it is termed as a basic authentication is that the username and password are only and only encoded by using base64 but is neither encrypted nor hashed. Though this makes the application easier and more prone to being compromised, only encoding makes way for many use cases where complex advanced authentication is not required as not much sensitive data is shared and this makes the application easier to build and maintain and obviously scale!
Now in order to understand how to perform basic authentication in spring, there are some pre-requisites that will be required in order to fulfill the task at hand. BasicAuthenticationFilter is the class we use in order to fulfill the required task of processing basic authentication by presenting the credentials into an HTTP header and the result after the authentication back into the SecurityContextHolder. In order to perform basic authentication, we should be mindful of a few things listed below:
- JDK
- Spring Boot
- IDE (preferably eclipse, but one may choose as per the convenience)
- Maven
Now we would need to incorporate the maven dependencies without which building an HTTP authentication is baseless. The first one is spring-boot-starter-parent which takes care of providing useful maven defaults. The dependency management section is provided so that the developer can omit any version tags of dependencies that are existing. The other one is spring-boot-starter-web which takes care of dependencies that are required to build a web app and finally spring-boot-starter-security which takes care of the security portion or in other words the basic authentication (for the purpose of the article). Once the dependencies are loaded, the bean needs to be configured post which the main configuration for spring security needs to be defined. @EnableWebSecurity is the decorator that enables the security service and the developer can extend adapters to override some spring features. Next, we would need to define the authentication entry point. This class makes sure to send responses when the credentials are no longer valid. In case the authorization is successful or non-attempted because of the HTTP header not containing supported request type the flow will continue.
Now that the back-end portion of setting up the authentication layer is complete; we would need to define the controller class where the APIs are exposed. Through the expose of API, one can easily look at the basic authentication at work! But the story is still incomplete as without a log-out implementation the authentication object that contains the credentials, roles, principles, and so on might be at risk of compromise. Hence the clearing of this context is an inevitable step and for this spring provides a SecurityContextLogoutHandler that takes care of the logout task and this is achieved by modifying the SecurityContextHandler.
Once the above pointers are followed in order to perform the basic authentication, we would need to run the application as a java application and let the code written do its job. In order to test, we can use a postman to carry out some GET or POST requests so as to see if the application is performing the required task! In the next section, we will look at a simple example of the implementation of basic authentication.
Examples
Defining the java files:
BasicauthConfig.java
package com.demo.educba.basicauth;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class BasicauthConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("eduCBA_premium")
.password("pa55word@")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
WebConfigCustom.java
package com.demo.educba.basicauth;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfigCustom implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
SecuringWebApplication.java
package com.demo.educba.basicauth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SecuringWebApplication {
public static void main(String[] args) throws Throwable {
SpringApplication.run(SecuringWebApplication.class, args);
}
}
Output:
Build JAR file using maven and running it:
Home Page
Entering the wrong username and password
Entering correct username (eduCBA_premium) and password (pa55word@)
Sign out
Conclusion
To conclude, in this article we have learned the usage of basic authentication using spring boot along with hands-on execution. Next, we encourage readers to try more example hands-on and take it a step forward with advanced authentication.
Recommended Articles
This is a guide to Spring Boot Basic Authentication. Here we discuss definition, syntax, How to perform Spring Boot Basic Authentication? examples with code implementation. You may also have a look at the following articles to learn more –