Streamlining your web application's login process is crucial for enhancing user experience and driving business growth. Spring Boot, a robust Java framework, provides numerous out-of-the-box solutions for handling user authentication, including the Spring Security module. In this comprehensive tutorial, we'll guide you through creating a reliable and secure login system using Spring Boot and Spring Security.

By the end of this tutorial, you'll have a solid understanding of how to implement user authentication in your Spring Boot application, from setting up the development environment to deploying your secure application. Let's dive right in!

Setting Up the Spring Boot Project
Before we delve into user authentication, let's first set up a basic Spring Boot project using Spring Initializr (https://start.spring.io/). Initialize your project with the following dependences:

- Web
- Spring Security
Creating the Database

For this tutorial, we'll use an in-memory H2 database. Add the following properties to your application.properties file:
spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=H2Dialect
Creating the User Entity

Now, let's create a simple User entity with fields for username and password. Create a new class named User.java inside the model package and paste the following code:
package com.example.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@NoArgsConstructor
public class User {
@Id
@GeneratedValue
private Long id;
private String username;
private String password;
}
Configuring Spring Security

Now that our project is set up, it's time to configure Spring Security. In this section, we'll create a custom UserDetailsService implementation and configure the Spring Security filter chain.
First, create a new class named UserDetailsServiceImpl.java inside the service package:
![Spring Boot Backend + Vuejs Example [Java tutorial] - Part 1](https://i.pinimg.com/originals/48/c5/e2/48c5e2e190f6350a56564ceb0718f3c9.png)








Implementing UserDetailsService
Spring Security uses the UserDetailsService interface to load user-specific data. Our implementation will simply retrieve the user from the database and return it as a UserDetails object.
package com.example.demo.service;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import lombok.AllArgsConstructor;
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return org.springframework.security.core.userdetails.User.withDefaultPasswordEncoder()
.username(user.getUsername())
.password(user.getPassword())
.roles("USER")
.build();
}
}
Configuring the FilterChain
Next, we'll configure the Spring Security filter chain using a custom WebSecurityConfigurerAdapter implementation. Create a new class named SecurityConfig.java inside the config package:
package com.example.demo.config;
import org.springframework.security.config.annotation.web.builders.WebSecurityFilterChain;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import lombok.AllArgsConstructor;
import static org.springframework.security.config.Customizer.withDefaults;
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.requestMatchers(new AntPathRequestMatcher("/login**")).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.csrf().disable();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Implementing the Login Page
Now that our security configuration is in place, let's create a simple login page for our users. Create a new controller class named AuthController.java inside the controller package:
Creating the Login Page
In this section, we'll create a get request handler for our login page and implement a post request handler for processing user login attempts.
package com.example.demo.controller;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import com.example.demo.model.User;
import com.example.demo.service.UserDetailsServiceImpl;
import lombok.AllArgsConstructor;
import static org.springframework.http.HttpStatus.OK;
@Controller
@AllArgsConstructor
public class AuthController {
private final AuthenticationManager authenticationManager;
@GetMapping("/login")
public ModelAndView login(@ModelAttribute("user") User user) {
return new ModelAndView("login", "user", user);
}
@PostMapping("/login")
public ModelAndView login(@ModelAttribute("user") User user) {
Authentication request = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
Authentication result = authenticationManager.authenticate(request);
if (result == null) {
return new ModelAndView("login", "user", user);
}
return new ModelAndView("redirect:/", "status", OK);
}
}
Don't forget to create a login.html page in your resources/templates folder using Thymeleaf as your templating engine. You can find a simple example of a login.html file in the Spring Security project samples (https://github.com/spring-projects/spring-security/tree/main/samples/boot/initial).
And that's it! You've successfully implemented a secure login system for your Spring Boot application using Spring Security. users can now securely log in to your application, and you can build upon this foundation to implement more features and enhance your user experience.
Next steps might include integrating social login providers like Google or Facebook, implementing password resets, or adding user registration functionality. Remember to always follow best practices for securing your application and protecting user data.
Happy coding!