If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:
>> LEARN SPRING SECURITYMocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
This tutorial will explain how to set up, configure, and customize Basic Authentication with Spring. Weβre going to build on top of the simple Spring MVC example, and secure the UI of the MVC application with the Basic Auth mechanism provided by Spring Security.
Further reading:
Spring Boot Security Auto-Configuration
Spring Security Authentication Provider
Spring Security Form Login
2. The Spring Security Configuration
We can configure Spring Security using Java config:
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter {
@Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user1")
.password(passwordEncoder().encode("user1Pass"))
.authorities("ROLE_USER");
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(expressionInterceptUrlRegistry ->
expressionInterceptUrlRegistry.requestMatchers("/securityNone").permitAll()
.anyRequest().authenticated())
.httpBasic(httpSecurityHttpBasicConfigurer -> httpSecurityHttpBasicConfigurer.authenticationEntryPoint(authenticationEntryPoint));
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Here weβre using the httpBasic() element to define Basic Authentication inside the SecurityFilterChain bean.
We could achieve the same result using XML as well:
<http pattern="/securityNone" security="none"/>
<http use-expressions="true">
<intercept-url pattern="/**" access="isAuthenticated()" />
<http-basic />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="{noop}user1Pass" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Whatβs relevant here is the <http-basic> element inside the main <http> element of the configuration. This is enough to enable Basic Authentication for the entire application. Since weβre not focusing on the Authentication Manager in this tutorial, weβll use an in-memory manager with the user and password defined in plain text.
The web.xml of the web application enabling Spring Security has already been discussed in the Spring Logout tutorial.
3. Consuming the Secured Application
The curl command is our go-to tool for consuming the secured application.
First, letβs try to request the /homepage.html without providing any security credentials:
curl -i http://localhost:8080/spring-security-rest-basic-auth/api/foos/1
We get back the expected 401 Unauthorized and the Authentication Challenge:
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=E5A8D3C16B65A0A007CFAACAEEE6916B; Path=/spring-security-mvc-basic-auth/; HttpOnly
WWW-Authenticate: Basic realm="Spring Security Application"
Content-Type: text/html;charset=utf-8
Content-Length: 1061
Date: Wed, 29 May 2013 15:14:08 GMT
Normally the browser would interpret this challenge and prompt us for credentials with a simple dialog, but since weβre using curl, this isnβt the case.
Now letβs request the same resource, the homepage, but provide the credentials to access it as well:
curl -i --user user1:user1Pass
http://localhost:8080/spring-security-rest-basic-auth/api/foos/1
As a result, the response from the server is 200 OK along with a Cookie:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=301225C7AE7C74B0892887389996785D; Path=/spring-security-mvc-basic-auth/; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-US
Content-Length: 90
Date: Wed, 29 May 2013 15:19:38 GMT
From the browser, we can consume the application normally; the only difference is that a login page is no longer a hard requirement since all browsers support Basic Authentication, and use a dialog to prompt the user for credentials.
4. Further Configuration β the Entry Point
By default, the BasicAuthenticationEntryPoint provisioned by Spring Security returns a full page for a 401 Unauthorized response back to the client. This HTML representation of the error renders well in a browser. Conversely, itβs not well suited for other scenarios, such as a REST API where a json representation may be preferred.
The namespace is flexible enough for this new requirement as well. To address this, the entry point can be overridden:
<http-basic entry-point-ref="myBasicAuthenticationEntryPoint" />
The new entry point is defined as a standard bean:
@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(
HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
throws IOException, ServletException {
response.addHeader("WWW-Authenticate", "Basic realm="" + getRealmName() + """);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 - " + authEx.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("Baeldung");
super.afterPropertiesSet();
}
}
By writing directly to the HTTP Response, we now have full control over the format of the response body.
5. The Maven Dependencies
The Maven dependencies for Spring Security have been discussed before in the Spring Security with Maven article. We will need both spring-security-web and spring-security-config available at runtime.
6. Conclusion
In this article, we secured an MVC application with Spring Security and Basic Authentication. We discussed the XML configuration, and we consumed the application with simple curl commands. Finally, we took control of the exact error message format, moving from the standard HTML error page to a custom text or JSON format.
When the project runs locally, the sample HTML can be accessed at:
http://localhost:8080/spring-security-rest-basic-auth/api/foos/1.
