Spring Boot Backend Development Course, Implementing Login and Logout with Spring Security, User Registration, Running Tests

Hello! In this course, we will learn how to develop a backend application using Spring Boot and implement user authentication functionality through Spring Security. This course is suitable for beginners to intermediate learners, and each step will be explained in detail.

1. What is Spring Boot?

Spring Boot is a Java-based framework that simplifies the complex configurations of the existing Spring framework, making it easier to develop applications. It features auto-configuration and allows for quick project starts through various starter dependencies.

1.1 Features of Spring Boot

  • Auto-configuration: Automatically configures settings as needed, reducing the need for developers to manually set them up.
  • Starter dependencies: Provides pre-configured dependencies to easily use multiple libraries.
  • Production-ready: Facilitates deployment and operation through an embedded server, monitoring tools, etc.

2. Setting Up a Project

To set up a Spring Boot project, you can use an IDE like IntelliJ IDEA or set it up directly using Spring Initializr. Here, we will create a project using Spring Initializr.

2.1 Using Spring Initializr

  1. Visit Spring Initializr.
  2. Configure as follows:
    • Project: Gradle Project
    • Language: Java
    • Spring Boot: 2.5.4 (select an appropriate version)
    • Group: com.example
    • Artifact: demo
    • Dependencies: Spring Web, Spring Data JPA, Spring Security, H2 Database, Lombok
  3. Click the Generate button to download the project.

3. Introduction to Key Libraries and Technologies

Now that the project is created, let’s briefly introduce each library and technology.

3.1 Spring Web

Spring Web is a module for developing web applications. It supports RESTful web services and the MVC pattern.

3.2 Spring Data JPA

Spring Data JPA is a module designed to simplify interactions with databases, based on JPA (Java Persistence API). It allows for processing databases in an object-oriented manner using ORM (Object Relational Mapping).

3.3 Spring Security

Spring Security is a powerful security framework that supports authentication and authorization in applications. It provides access control for specific URLs, user authentication, and session management features.

3.4 H2 Database

H2 Database is a lightweight in-memory database written in Java. It can be very useful in development and testing stages.

4. Implementing User Registration Feature

The user registration feature is one of the basic functionalities of the application, responsible for storing user information in the database.

4.1 Creating Entity Class

Create a User entity class to store user information.

        
        package com.example.demo.model;

        import javax.persistence.*;

        @Entity
        @Table(name = "users")
        public class User {
            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            private Long id;

            @Column(nullable = false, unique = true)
            private String username;

            @Column(nullable = false)
            private String password;

            @Column(nullable = false)
            private String email;

            // Getters and Setters
        }
        
        

4.2 Creating Repository Interface

Create a UserRepository interface that can interact with the database.

        
        package com.example.demo.repository;

        import com.example.demo.model.User;
        import org.springframework.data.jpa.repository.JpaRepository;

        public interface UserRepository extends JpaRepository {
            User findByUsername(String username);
        }
        
        

4.3 Creating Registration Service

Create a UserService class to handle the registration logic.

        
        package com.example.demo.service;

        import com.example.demo.model.User;
        import com.example.demo.repository.UserRepository;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.security.crypto.password.PasswordEncoder;
        import org.springframework.stereotype.Service;

        @Service
        public class UserService {
            @Autowired
            private UserRepository userRepository;

            @Autowired
            private PasswordEncoder passwordEncoder;

            public void registerUser(User user) {
                user.setPassword(passwordEncoder.encode(user.getPassword()));
                userRepository.save(user);
            }
        }
        
        

4.4 Creating Registration Controller

Create a UserController to handle HTTP requests.

        
        package com.example.demo.controller;

        import com.example.demo.model.User;
        import com.example.demo.service.UserService;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.*;

        @RestController
        @RequestMapping("/api/users")
        public class UserController {
            @Autowired
            private UserService userService;

            @PostMapping("/register")
            public String register(@RequestBody User user) {
                userService.registerUser(user);
                return "Registration successful";
            }
        }
        
        

5. Configuring Spring Security

Now we will configure Spring Security to implement login and logout features.

5.1 Implementing WebSecurityConfigurerAdapter

Create a class for Spring Security configuration. Inherit from WebSecurityConfigurerAdapter to implement security settings.

        
        package com.example.demo.config;

        import com.example.demo.service.CustomUserDetailsService;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.context.annotation.Bean;
        import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
        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.crypto.bcrypt.BCryptPasswordEncoder;
        import org.springframework.security.crypto.password.PasswordEncoder;

        @EnableWebSecurity
        public class SecurityConfig extends WebSecurityConfigurerAdapter {
            @Autowired
            private CustomUserDetailsService userDetailsService;

            @Override
            protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
            }

            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/api/users/register").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                    .logout()
                    .permitAll();
            }

            @Bean
            public PasswordEncoder passwordEncoder() {
                return new BCryptPasswordEncoder();
            }
        }
        
        

5.2 Creating Class for User Details

Create a CustomUserDetailsService class to handle user authentication information in Spring Security.

        
        package com.example.demo.service;

        import com.example.demo.model.User;
        import com.example.demo.repository.UserRepository;
        import org.springframework.beans.factory.annotation.Autowired;
        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;

        @Service
        public class CustomUserDetailsService implements UserDetailsService {
            @Autowired
            private 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 new org.springframework.security.core.userdetails.User(user.getUsername(),
                        user.getPassword(), new ArrayList<>());
            }
        }
        
        

5.3 Creating Login Page HTML

Create an HTML file for the login page. Write the following code in src/main/resources/templates/login.html.

        
        <!DOCTYPE html>
        <html>
        <head>
            <title>Login</title>
        </head>
        <body>
            <h1>Login</h1>
            <form action="/login" method="post">
                <label for="username">Username:</label>
                <input type="text" id="username" name="username"><br>
                <label for="password">Password:</label>
                <input type="password" id="password" name="password"><br>
                <input type="submit" value="Login">
            </form>
            <div>
                <a href="/api/users/register">Register</a>
            </div>
        </body>
        </html>        
        
        

6. Running and Testing

Now that all settings are complete, let’s run the Spring Boot application.

6.1 Running the Application

Run the DemoApplication class from the IDE or start the application via command.

        
        mvn spring-boot:run
        
        

6.2 Testing User Registration

You can use API testing tools like Postman to test user registration. Let’s send a POST request like the following:

        
        POST /api/users/register
        Content-Type: application/json

        {
            "username": "testuser",
            "password": "password123",
            "email": "testuser@example.com"
        }
        
        

6.3 Testing Login

After registering, access the login page and enter the created user information to log in.

Conclusion

In this course, we have looked into how to develop a backend application using Spring Boot and implement login and user registration features utilizing Spring Security. You can apply these in real projects to add more advanced features or integrate with external APIs.

If you have any questions or need further assistance, please leave a comment. Thank you!