Spring Boot Backend Development Course, Implementing Login and Logout with Spring Security, Testing Logout Execution

Introduction

This course covers backend development using Spring Boot. In particular, we will learn how to implement login/logout functionality and a registration system through Spring Security. By the end of this course, you will be able to build a complete user authentication and authorization system. This guide is prepared for those who are new to Spring Boot and Security, and it explains the process step by step.

Basic Environment Setup

Before starting a Spring Boot project, we need to set up the necessary environment. JDK and Maven should be installed, and it is recommended to use an IDE such as IntelliJ IDEA or Eclipse.

  • Install JDK 8 or higher
  • Install Maven or Gradle
  • Install IDE (e.g., IntelliJ IDEA, Eclipse)

Creating a Spring Boot Project

You can create a Spring Boot project using Spring Initializr. Select the following options to generate the project:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.5.x (or latest version)
  • Dependencies: Spring Web, Spring Security, Spring Data JPA, H2 Database

After generating the project, download the zip file and extract it in your desired directory. Open the project in your IDE and check if the necessary libraries are included.

Spring Security Configuration

We will implement basic authentication functionality using Spring Security. First, write the SecurityConfig class to define user authentication settings.

        java
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        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;

        @Configuration
        @EnableWebSecurity
        public class SecurityConfig extends WebSecurityConfigurerAdapter {
            @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");
            }

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

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

Implementing Registration Functionality

We will implement a REST API for user registration. We will use JPA to store user information. Create a User entity class to define user data.

        java
        import javax.persistence.Entity;
        import javax.persistence.GeneratedValue;
        import javax.persistence.GenerationType;
        import javax.persistence.Id;

        @Entity
        public class User {
            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            private Long id;
            private String username;
            private String password;
            private String role;

            // getters and setters
        }
        
    

Creating UserRepository Interface

Create a Repository interface to store user information.

        java
        import org.springframework.data.jpa.repository.JpaRepository;

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

Implementing Registration REST API

Write a controller class to handle registration. It will store the user’s information in the database based on what the user inputs.

        java
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.*;

        @RestController
        @RequestMapping("/api")
        public class UserController {
            @Autowired
            private UserRepository userRepository;

            @PostMapping("/register")
            public String register(@RequestBody User user) {
                user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
                userRepository.save(user);
                return "Registration successful!";
            }
        }
        
    

Testing Login and Logout Functionality

Now we are ready to test the login and logout functionalities. You can use tools like Postman or cURL to test the REST APIs.

Testing Registration

To test the registration API, send a POST request like the following:

        bash
        curl -X POST http://localhost:8080/api/register -H "Content-Type: application/json" -d '{"username":"testuser", "password":"testpassword"}'
        
    

You will receive “Registration successful!” in response.

Testing Login

The login test will proceed with the following POST request.

        bash
        curl -X POST -d "username=testuser&password=testpassword" http://localhost:8080/login
        
    

If the request is successful, you will receive a login success message as a response.

Testing Logout

The logout test will proceed with the following GET request.

        bash
        curl -X GET http://localhost:8080/logout
        
    

If the request is successful, you will receive a logout success message as a response.

Conclusion

In this course, we have implemented backend development using Spring Boot, along with login, logout, and registration functionalities through Spring Security. Through this process, you have gained the basics needed to create a secure web application. We encourage you to continue using Spring Boot and Security to implement more complex features.

Additional Resources