Implementing User Authentication in a Spring Boot Application: A Detailed Step-by-Step Guide

Abhinav
3 min readJul 14, 2023

--

User authentication is a critical component of web applications, providing secure access to user accounts and protecting sensitive information. In this article, we will demonstrate how to implement user authentication using the Spring Boot framework. Spring Boot simplifies the development process with its powerful features and tools. We will guide you through the steps, including creating a User entity, implementing authentication logic, configuring Spring Security, and creating login and registration endpoints, with detailed code examples.

Prerequisites

To follow along, you should have a basic understanding of Java, Spring Boot, and RESTful API development. Familiarity with concepts like controllers, services, and data persistence using an Object-Relational Mapping (ORM) framework like Spring Data JPA will be helpful.

Table of Contents

  1. Setting Up a Spring Boot Project
  2. Creating a User Entity
  3. Implementing the UserDetailsService
  4. Configuring Spring Security
  5. Creating Login and Registration Endpoints
  6. Conclusion

1. Setting Up a Spring Boot Project

Start by creating a new Spring Boot project using your preferred IDE or the Spring Initializr website. Include the following dependencies in your project configuration: Spring Web, Spring Data JPA, Spring Security, and any additional libraries required.

2. Creating a User Entity

Create a User entity that represents the application’s users. The User entity should include fields like id, username, password, email, and other relevant user details. Annotate the entity class with JPA annotations to map it to a database table. Implement the UserDetails interface provided by Spring Security to handle user details and security-related functionalities. Here’s an example:

@Entity
@Table(name = "users")
public class User implements UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String username;
private String password;
private String email;
// Other fields and relationships
// Implement UserDetails methods and other required methods
// Getters and setters
}

3. Implementing the UserDetailsService

Create a UserDetailsService implementation to load user details during the authentication process. This implementation should interact with a UserRepository to fetch the User entity from the database. Here’s an example:

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

private final UserRepository userRepository;
public UserDetailsServiceImpl(UserRepository userRepository) {
this.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 user;
}
}

4. Configuring Spring Security

Configure Spring Security to enable user authentication and authorization. Create a SecurityConfig class that extends WebSecurityConfigurerAdapter and override the necessary methods. Configure the authentication manager to use the UserDetailsService implementation created earlier. Additionally, define security rules for protected resources and endpoints. Here’s an example:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private final UserDetailsService userDetailsService;
public SecurityConfig(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/api/login")
.permitAll()
.and()
.logout()
.logoutUrl("/api/logout")
.permitAll();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

5. Creating Login and Registration Endpoints

Create a UserController class to handle login and registration endpoints. Define methods annotated with @PostMapping to handle the appropriate requests. Inside these methods, interact with a UserService to handle the actual authentication and registration logic. Here’s an example:

@RestController
@RequestMapping("/api")
public class UserController {

private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody UserRegistrationDTO userDTO) {
userService.registerUser(userDTO);
return ResponseEntity.ok("User registered successfully");
}
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody UserLoginDTO userDTO) {
// Perform authentication logic
// Return appropriate response or token
return ResponseEntity.ok("Login successful");
}
@PostMapping("/logout")
public ResponseEntity<?> logout() {
// Perform logout logic
// Invalidate token or session
return ResponseEntity.ok("Logout successful");
}
}

Conclusion

In this article, we demonstrated how to implement user authentication in a Spring Boot application. We covered setting up a Spring Boot project, creating a User entity, implementing the UserDetailsService, configuring Spring Security, and creating login and registration endpoints. By following these steps and using the provided code examples, you can establish a secure authentication system in your Spring Boot application. Remember to adapt the code to fit your specific requirements and consider additional security measures like password hashing, session management, and account recovery for a comprehensive authentication system.

--

--

Abhinav

Hi, I'm Abhinav, a software engineer with a passion for continuous learning and exploring new technologies.