
February 12, 2025
Spring Security Basics: Adding Authentication to Your Application
What protects your app against unauthorized access? Data breaches and threats make user authentication essential. A simple online app or a complex enterprise system must restrict crucial data access to authorized users.
In this article, we will use Spring Security's advanced security capabilities to provide simple user authentication to a Java application. This article will help you set up a secure login system that restricts page access by user role.
Setting Up the Spring Security Environment
Set up our environment before authentication. Spring Boot with Spring Security will authenticate. Spring Initializr makes it easy to build a Spring Boot project.
Here's what you'll need:
- Java 8 or above
- Maven or Gradle (for dependency management)
- Spring Boot (a quick way to get started)
Insert the relevant dependencies into pom.xml or build.gradle. And, in your Maven pom.xml, add this snippet:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
With these dependencies, Spring Security automatically configures basic authentication. Now we will customize it so it works for us.
Configuring Basic Authentication
Spring Security simplifies user authentication with a few lines of code. In-memory authentication stores user credentials and responsibilities in the program for simplicity.
Here's how you can configure it in your application:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("password")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
In this code:
- Set HTTP security with configure(HttpSecurity http), allowing login page access and requiring authentication for other pages.
- In-memory authentication is defined by configure(AuthenticationManagerBuilder auth), creating two users (user and admin) with roles USER and ADMIN.
- We encrypt user passwords using BCryptPasswordEncoder for enhanced protection.
Creating a Simple Login Page
Create a simple login page now that authentication logic is in place. Spring Security automatically leads unauthenticated visitors to the login page, but you may customize the HTML form for usability.
Here's a simple login form:
<form action="/login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
This form accepts credentials. Spring Security validates the credentials and gives access or redirects users to the login page if authentication fails when they submit the form.
Securing Access to Resources
After authentication, limit resource access by user role. For instance, you might only want ADMIN users to get to the /admin page and USER users to get to the /user page.
Here's how to secure URLs based on roles:
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated();
Spring Security will only allow ADMIN users to access /admin URLs and USER users to access /user URLs with this setup.
For further control, employ method-level security annotations like @PreAuthorize.
Handling Login Failures
Feedback is vital when login fails due to an invalid username or password. Spring Security handles login failure automatically, but you can modify the error message.
To show a custom error page or redirect on failure, apply this configuration:
.formLogin()
.failureUrl("/login?error=true")
.defaultSuccessUrl("/home", true);
If login fails, this sends users to /login?error=true. The login page might also display an error message to warn users of the failure.
Conclusion
This post has covered Spring Security authentication basics for Java applications. Established the project environment, established in-memory authentication, generated a custom login page, protected resource access by role, and handled login failures.
Your first step toward establishing a secure Java application was following these steps. Spring Security offers complex features like JWT-based authentication and OAuth2 that you may use as your application expands.
253 views