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

Implementing Login/Logout and User Registration with Spring Security

Hello, today we will conduct a backend development course using Spring Boot. In this course, we will take a detailed look at how to implement login and logout functionalities, as well as user registration using Spring Security. Spring Boot is a framework that allows for rapid and easy development of Java-based web applications, and we will be covering the process of building powerful and secure web applications through it.

1. Setting Up the Development Environment

Before we start the course, we need to set up the development environment. Below are the necessary tools and setup methods.

  • Java Development Kit (JDK) 11 or higher
  • Spring Boot 2.5.x or higher
  • IDE such as IntelliJ IDEA or Eclipse
  • Gradle or Maven (build tool)
  • H2 Database (embedded database)

2. Creating a Spring Boot Project

To create a Spring Boot project, we will use Spring Initializr. Please follow the steps below to set up the project.

  1. Access Spring Initializr in your web browser.
  2. Enter the project metadata.
    • Project: Maven Project or Gradle Project
    • Language: Java
    • Spring Boot: Set to 2.x.x
    • Group: com.example
    • Artifact: demo
    • Name: demo
    • Description: Spring Boot demo project
    • Package name: com.example.demo
    • Packaging: Jar
    • Java: 11
  3. Select the following under Dependencies.
    • Spring Web
    • Spring Security
    • Spring Data JPA
    • H2 Database
  4. Click the Generate button to download the project ZIP file.

3. Project Structure

When you open the project, a basic package structure is created. Here’s an explanation of the roles of the main directories and files.

  • src/main/java/com/example/demo: Directory where Java source files are located.
  • src/main/resources/application.properties: Application settings file.
  • src/test/java/com/example/demo: Directory where test files are located.

4. Configuring Spring Security

We will set up Spring Security to implement the login and logout functionalities.

4.1 Adding Dependencies

Add the necessary dependencies to the pom.xml or build.gradle file. If you are using Maven, please add the following dependency.

        
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
        
    

4.2 Creating SecurityConfig Class

Create a SecurityConfig class to define the configuration for Spring Security.

        
            package com.example.demo.config;

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

            @Configuration
            @EnableWebSecurity
            public class SecurityConfig extends WebSecurityConfigurerAdapter {
                
                @Override
                protected void configure(HttpSecurity http) throws Exception {
                    http
                        .authorizeRequests()
                        .antMatchers("/register", "/h2-console/**").permitAll()
                        .anyRequest().authenticated()
                        .and()
                        .formLogin()
                        .loginPage("/login")
                        .permitAll()
                        .and()
                        .logout()
                        .permitAll();
                }

                @Bean
                public void init() {
                    // Configuration for using H2 Console
                    java.sql.Connection conn = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", "");
                    conn.createStatement().execute("SET MODE MySQL");
                }
            }
        
    

5. Implementing User Registration Functionality

Now we will implement basic user registration functionality.

5.1 Creating User Entity

Create a User entity class to store user information.

        
            package com.example.demo.model;

            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;

                // getters and setters
            }
        
    

5.2 Creating UserRepository Interface

Create a UserRepository to manage user information.

        
            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);
            }
        
    

5.3 Creating UserService Class

Create a UserService class to handle the user 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.bcrypt.BCryptPasswordEncoder;
            import org.springframework.stereotype.Service;

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

                @Autowired
                private BCryptPasswordEncoder passwordEncoder;

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

                public User findByUsername(String username) {
                    return userRepository.findByUsername(username);
                }
            }
        
    

5.4 Creating RegistrationController Class

Create a RegistrationController class to handle the user registration page and logic.

        
            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.stereotype.Controller;
            import org.springframework.ui.Model;
            import org.springframework.web.bind.annotation.GetMapping;
            import org.springframework.web.bind.annotation.PostMapping;
            import org.springframework.web.bind.annotation.ModelAttribute;

            @Controller
            public class RegistrationController {

                @Autowired
                private UserService userService;

                @GetMapping("/register")
                public String showRegistrationForm(Model model) {
                    model.addAttribute("user", new User());
                    return "register";
                }

                @PostMapping("/register")
                public String registerUser(@ModelAttribute User user) {
                    userService.register(user);
                    return "redirect:/login";
                }
            }
        
    

5.5 Creating HTML View Template

Create the user registration HTML view. Write the following in the templates/register.html file.

        
            <!DOCTYPE html>
            <html xmlns:th="http://www.thymeleaf.org">
            <head>
                <title>User Registration</title>
            </head>
            <body>
                <h1>User Registration</h1>
                <form action="#" th:action="@{/register}" th:object="${user}" method="post">
                    <div>
                        <label for="username">Username:</label>
                        <input type="text" th:field="*{username}" required/>
                    </div>
                    <div>
                        <label for="password">Password:</label>
                        <input type="password" th:field="*{password}" required/>
                    </div>
                    <div>
                        <button type="submit">Register</button>
                    </div>
                </form>
            </body>
            </html>
        
    

6. Implementing Login Functionality

Now we will implement the login feature. Since Spring Security handles user authentication, we only need to implement parts related to user information.

6.1 Modifying SecurityConfig

Set the user authentication information in SecurityConfig.

        
            import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

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

6.2 Implementing UserDetailsService

Create a UserDetailsService to handle user authentication information.

        
            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;

            @Service
            public class CustomUserDetailsService implements UserDetailsService {
                
                @Autowired
                private UserService userService;

                @Override
                public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                    User user = userService.findByUsername(username);
                    if (user == null) {
                        throw new UsernameNotFoundException("Cannot find user: " + username);
                    }
                    return org.springframework.security.core.userdetails.User.withUsername(user.getUsername())
                            .password(user.getPassword())
                            .roles("USER")
                            .build();
                }
            }
        
    

7. Login and Logout Pages

Implement the login page and logout confirmation page.

7.1 Creating login.html Template

        
            <!DOCTYPE html>
            <html xmlns:th="http://www.thymeleaf.org">
            <head>
                <title>Login</title>
            </head>
            <body>
                <h1>Login</h1>
                <form action="#" th:action="@{/login}" method="post">
                    <div>
                        <label for="username">Username:</label>
                        <input type="text" name="username" required/>
                    </div>
                    <div>
                        <label for="password">Password:</label>
                        <input type="password" name="password" required/>
                    </div>
                    <div>
                        <button type="submit">Login</button>
                    </div>
                </form>
            </body>
            </html>
        
    

7.2 Creating logout.html Template

        
            <!DOCTYPE html>
            <html xmlns:th="http://www.thymeleaf.org">
            <head>
                <title>Logout</title>
            </head>
            <body>
                <h1>You have been logged out.</h1>
                <a href="/login">Go to login page</a>
            </body>
            </html>
        
    

8. Running and Testing

Now that we have completed all the settings and implementations, let’s run and test the application.

8.1 Running the Application

Run the application. Execute the following command through the IDE’s Run command or Terminal.

        
            ./mvnw spring-boot:run
        
    

In the browser, enter http://localhost:8080/register to navigate to the user registration page.

8.2 Testing User Registration

Test user registration by entering a username and password. After registration, proceed to http://localhost:8080/login and test the login functionality.

8.3 Testing Login and Logout

After logging in successfully, click the logout button to check if the logout works properly.

9. Conclusion

In this course, we learned how to implement login, logout, and user registration functions using Spring Security with Spring Boot. With these fundamental features, you have laid the foundation for securely operating your own web application. Explore additional features using Spring Boot to develop a more advanced web application!

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

Spring Boot Backend Development Course, Implementing Login and Logout with Spring Security, User Registration, Adding Logout View

In this lecture, we will mainly cover how to implement login/logout functionality and user registration using Spring Security while developing the backend with Spring Boot. We will also explain how to add a logout view in detail. This course will start from a basic Spring Boot project and progressively add the necessary features.

1. Spring Boot Project Setup

Spring Boot is a framework that helps you quickly develop web applications based on Java. In this course, we will set up the project using the latest version of Spring Boot. Here are the steps to set up a Spring Boot project.

1. Generate a basic project using Spring Initializr
   - Go to https://start.spring.io/.
   - Project: Maven Project
   - Language: Java
   - Spring Boot: Select the latest version
   - Set Project Metadata:
     - Group: com.example
     - Artifact: demo
   - Add Dependencies:
     - Spring Web
     - Spring Security
     - Spring Data JPA
     - H2 Database (Embedded Database)
   - Click the Generate button to download the ZIP file and extract it

1.1. Open the Project in IDE

Open the downloaded project in your IDE. You can use IDEs like IntelliJ IDEA or Eclipse. Each IDE will automatically download the dependency libraries via Maven.

2. Design Domain Model

Design the domain model to store user information for registration and login. Create a class called User and map it to the database using JPA.

package com.example.demo.model;

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 email;

    // Getter and Setter
}

2.1. Create User Repository

Create a UserRepository interface to manipulate user data. Extend JPA’s CrudRepository to provide basic CRUD functionality.

package com.example.demo.repository;

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

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

3. Configure Spring Security

Configure Spring Security to implement login and registration features. Spring Security is a powerful framework that enhances the security performance of applications.

3.1. Security Configuration Class

Create a class for Spring Security configuration. Write the SecurityConfig class to set up basic authentication and authorization settings.

package com.example.demo.config;

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 {
        // UserDetailsService and PasswordEncoder configuration
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/register").permitAll() // Allow everyone to access the registration page
                .anyRequest().authenticated() // Require authentication for other requests
                .and()
            .formLogin()
                .loginPage("/login") // Custom login page
                .permitAll()
                .and()
            .logout()
                .permitAll(); // Allow logout
    }

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

4. Implement Registration Functionality

Implement a REST Controller and registration view for the registration feature. Create a User object using the information inputted by the user, and store the password securely hashed.

4.1. Create User Controller Class

package com.example.demo.controller;

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.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/register")
public class UserController {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping
    public String registerUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword())); // Hash the password
        userRepository.save(user); // Save the user
        return "redirect:/login"; // Redirect to the login page after registration
    }
}

4.2. Registration View

Create a Thymeleaf view for registration. This will exist as an HTML file and provide a form for the user to input and submit their information.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Registration</title>
</head>
<body>
    <h1>Registration</h1>
    <form action="/register" 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>
        <label for="email">Email</label>
        <input type="email" id="email" name="email" required>
        <button type="submit">Register</button>
    </form>
</body>
</html>

5. Implement Login Functionality

Set up additional controllers and views for login functionality. Authentication will be based on the information inputted by the user during login.

5.1. Login Page Setup

Create an HTML file for the login page. It should include fields for entering the username and password.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <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" required>
        <label for="password">Password</label>
        <input type="password" id="password" name="password" required>
        <button type="submit">Login</button>
    </form>
    <a href="/register">Go to registration</a>
</body>
</html>

6. Implement Logout and Add View

Add logout functionality. Set it up so that users are redirected to the main screen after logging out.

6.1. Configure Logout Functionality

The logout functionality can be easily implemented through the already configured HttpSecurity. When a user requests to log out, the authentication session is invalidated and redirected.

6.2. Create Redirect Page After Logout

Create a page that users will see after logging out. Here, appropriate messages can be provided.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Logout</title>
</head>
<body>
    <h1>You have logged out.</h1>
    <p>Click the button below to log in again.</p>
    <a href="/login">Go to login page</a>
</body>
</html>

7. Conclusion and Next Steps

In this lecture, we have implemented login and logout functionalities, and user registration using Spring Security while developing the backend with Spring Boot. After mastering these basic functions, it is also possible to implement more extended functionalities such as JWT (JSON Web Token) based authentication, social login using OAuth2, and password reset functionalities.

Additionally, based on this course, I encourage you to learn advanced topics such as communication with web front-end through RESTful APIs, cloud deployment, and test and deployment automation.

I hope this helps you in your development journey, and if you have any questions or further inquiries, please leave a comment. Thank you!

Spring Boot Backend Development Course, Implementing Login and Logout with Spring Security, Adding Logout Method

In this course, we will cover authentication and authorization features to allow users to access applications in modern web applications. Specifically, we will implement user login, logout, and membership registration features using Spring Boot and Spring Security. This process will include basic features frequently used in real web services and will greatly help in understanding the importance of security.

Table of Contents

  1. Overview of Spring Boot
  2. Introduction to Spring Security
  3. Project Setup
  4. Implementing Membership Registration
  5. Implementing Login and Logout
  6. Adding Logout Method
  7. Course Summary

1. Overview of Spring Boot

Spring Boot is an extension of the Spring Framework designed to enable rapid development. It helps to easily start applications without complex configurations, and you can easily add necessary libraries through the starter packages provided on the official Spring Boot website.

Why use Spring Boot? One of the biggest advantages of Spring Boot is dependency management. You only need to configure the pom.xml file that includes various libraries, and it can automatically download the necessary dependencies as needed. Set it up simply and focus on implementing your ideas.

2. Introduction to Spring Security

Spring Security is a powerful framework responsible for the authentication and authorization of applications. With Spring Security, you can easily implement the following features:

  • User authentication: login functionality using username and password
  • Authorization for authenticated users
  • CSRF protection
  • Session management

Spring Security is very powerful in itself, but you can enjoy even more advantages when integrated with Spring Boot. It can be set up quickly and easily, and it allows for easier management of security issues.

3. Project Setup

Create a new web application using Spring Boot. Follow the steps below to set up the project.

3.1. Using Spring Initializr

You can create a new Spring Boot project using Spring Initializr (start.spring.io). Select the following dependencies:

  • Spring Web
  • Spring Security
  • Spring Data JPA
  • H2 Database

3.2. Project Code Structure

After creating the project, maintain the following basic code structure:

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── demo
│   │               ├── DemoApplication.java
│   │               ├── config
│   │               │   └── SecurityConfig.java
│   │               ├── controller
│   │               │   └── UserController.java
│   │               ├── model
│   │               │   └── User.java
│   │               └── repository
│   │                   └── UserRepository.java
│   └── resources
│       ├── application.properties
│       └── templates
└── test

4. Implementing Membership Registration

To implement the membership registration feature, we will define the User model and UserRepository, and then create the UserController to handle registration.

4.1. Defining the User Model


package com.example.demo.model;

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

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

    // Getters and Setters omitted
}

4.2. Implementing the UserRepository Interface


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. Implementing the UserController


package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

@Controller
@RequestMapping("/signup")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public String showSignupForm() {
        return "signup"; // signup.html
    }

    @PostMapping
    public String registerUser(@Valid User user) {
        userRepository.save(user);
        return "redirect:/login"; // Redirect to login page after registration
    }
}

4.4. Creating Membership Registration HTML Form

Create a resources/templates/signup.html file and write the following.






    
    Membership Registration


    

Membership Registration



5. Implementing Login and Logout

Now, let’s set up Spring Security to allow users to log in. We need to handle the authentication logic and set the target to redirect after login.

5.1. Configuring the SecurityConfig Class


package com.example.demo.config;

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(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/signup").permitAll() // Membership registration page is accessible to all
                .anyRequest().authenticated() // Other requests require authentication
            .and()
                .formLogin()
                .loginPage("/login") // Custom login page
                .permitAll()
            .and()
                .logout()
                .permitAll();
    }

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }

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

5.2. Creating the Login Page

Create a resources/templates/login.html file to add a custom login page.






    
    Login


    

Login



6. Adding Logout Method

The logout feature is provided by Spring Security by default, but additional customization may be needed. Set the URL for logging out and the URL to redirect after log out.

6.1. Configuring the Logout URL


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .logout()
                .logoutUrl("/logout") // Logout URL
                .logoutSuccessUrl("/login?logout") // URL to redirect after logout success
                .invalidateHttpSession(true) // Invalidate session
                .clearAuthentication(true); // Clear authentication information
    }
}

6.2. Adding a Logout Button

After logging in, let’s add a logout button to allow easy logout. Add the following in resources/templates/index.html.



    

Welcome!

Spring Boot Backend Development Course, Implementing Login and Logout with Spring Security, Implementing Sign Up, Implementing Logout

Implementing Login/Logout and Sign Up with Spring Security

Hello! In this tutorial, we will explore backend development using Spring Boot. The main goal of this tutorial is to implement login/logout and sign-up functionalities using Spring Security. The entire process will proceed through the following steps.

  • Setting up a Spring Boot project
  • Configuring Spring Security
  • Implementing sign-up functionality
  • Implementing login and logout functionality

1. Setting up a Spring Boot project

First, let’s set up a Spring Boot project. You can create a project using [Spring Initializr](https://start.spring.io/). Please select the following settings.

Project Settings

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.5.x (Select the latest stable version)
  • Dependencies:
    • Spring Web
    • Spring Security
    • Spring Data JPA
    • H2 Database (an in-memory database for development and testing purposes)

Once the settings are complete, you can download the ZIP file by clicking the GENERATE button. After downloading, extract the contents and open the project in your preferred IDE.

2. Configuring Spring Security

To configure Spring Security, create a class called SecurityConfig.java. This class will define the necessary configurations for user authentication and authorization.

package com.example.demo.config;

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");
    }

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

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

The code above shows how to configure user authentication and authorization, including an in-memory user store. It uses BCryptPasswordEncoder to encrypt passwords.

3. Implementing sign-up functionality

To implement sign-up functionality, we will create a User entity to store user information and a UserRepository interface to handle user data storage.

package com.example.demo.model;

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;

    // getters and setters
}
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);
}

Next, we will create a service and a controller to handle the sign-up process.

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 register(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }
}
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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class AuthController {

    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(User user) {
        userService.register(user);
        return "redirect:/login";
    }
}

Now let’s create the HTML form for the sign-up.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sign Up</title>
</head>
<body>
    <h1>Sign Up</h1>
    <form action="/register" method="post">
        <label for="username">Username</label>
        <input type="text" id="username" name="username" required><br>

        <label for="password">Password</label>
        <input type="password" id="password" name="password" required><br>

        <input type="submit" value="Register">
    </form>
</body>
</html>

4. Implementing login and logout functionality

Now, let’s implement the login page and the logout functionality. We will create another HTML for the login page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <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" required><br>

        <label for="password">Password</label>
        <input type="password" id="password" name="password" required><br>

        <input type="submit" value="Login">
    </form>
    <a href="/register">Sign Up</a>
</body>
</html>

The logout functionality is provided by Spring Security by default, so no additional implementation is necessary. When the logout endpoint is called, the session is terminated and the user is redirected to the login page.

5. Conclusion

In this tutorial, we laid the foundation for backend development using Spring Boot, learning how to implement login, logout, and sign-up functionalities utilizing Spring Security. This process will help you understand how to handle and manage user authentication in web applications. I hope you have established a base to advance to more sophisticated features. In the next tutorial, we will explore REST APIs and JWT authentication.

Thank you!