Spring Boot Backend Development Course, Implementing Login and Logout with Spring Security, Implementing Signup, Implementing View Controller

Hello! In this lecture, we will learn how to develop a basic backend application using Spring Boot. In particular, we will delve into implementing login and logout functionalities, user registration functionality using Spring Security, and enhancing the user experience through view controllers.

1. Introduction to Spring Boot and Security

Spring Boot is an application development tool based on the Spring Framework, designed to help you build applications quickly without complex configurations. Spring Security is a powerful tool for managing the security of applications and makes it easy to handle authentication and authorization.

1.1. Requirements

  • JDK 8 or higher
  • IDE (IntelliJ IDEA, Eclipse, etc.)
  • Maven or Gradle

1.2. Project Setup

To create a Spring Boot project, use Spring Initializr. Please add the following dependencies:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
    

2. Implementing User Registration Functionality

To register a user, follow these steps:

2.1. Creating an Entity

Create a User entity to hold user information.

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

        private String username;
        private String password;
        private String email;

        // Getters and Setters
    }
    

2.2. Creating a Repository Interface

Create a UserRepository to interact with the database using JPA.

    public interface UserRepository extends JpaRepository<User, Long> {
        Optional<User> findByUsername(String username);
    }
    

2.3. Writing a Service Class

Create a UserService class to handle registration logic.

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

        public User registerNewUser(User user) {
            // Additional business logic (e.g., password encryption)
            return userRepository.save(user);
        }
    }
    

2.4. Creating a Controller

Create a UserController that provides a REST API for user registration.

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

        @PostMapping("/register")
        public ResponseEntity<User> registerUser(@RequestBody User user) {
            User newUser = userService.registerNewUser(user);
            return ResponseEntity.ok(newUser);
        }
    }
    

2.5. Password Encryption

We will use bcrypt hash function to securely store passwords. The password will be encrypted in UserService.

    @Autowired
    private PasswordEncoder passwordEncoder;

    public User registerNewUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }
    

3. Implementing Login and Logout Functionality

Now that user registration is complete, we will implement the login and logout functionalities.

3.1. Spring Security Configuration

Set up Spring Security to implement basic user authentication. Write the SecurityConfig class.

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

3.2. Creating Login Page and Logout Functionality

Create a login page and implement logout functionality. The login page is written in HTML.

    <form action="/login" method="post">
        <label>Username:</label>
        <input type="text" name="username" required>
        <label>Password:</label>
        <input type="password" name="password" required>
        <button type="submit">Login</button>
    </form>
    

4. Implementing View Controller

Finally, we will create a view controller to add functionality for displaying data to the user.

4.1. Creating a Controller

Create a controller that returns HTML pages using Spring MVC’s view controllers.

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

        @GetMapping("/login")
        public String loginForm() {
            return "login";
        }
    }
    

4.2. Using Thymeleaf Templates

Use Thymeleaf to render HTML in the view layer. Add a register.html file to the resources/templates folder.

    <html xmlns:th="http://www.w3.org/1999/xhtml">
    <body>
        <form action="@{/api/users/register}" th:object="${user}" method="post">
            <label>Username:</label>
            <input type="text" th:field="*{username}" required>
            <label>Password:</label>
            <input type="password" th:field="*{password}" required>
            <button type="submit">Register</button>
        </form>
    </body>
    

5. Conclusion

You have now learned how to build a simple backend application with user registration, login, and logout functionality using Spring Boot. This serves as a foundation for developing more complex applications using Spring Boot. Next steps may include database integration, API documentation, and frontend integration. If you have any questions or need further assistance, please leave a comment!

© 2023 Your Blog Name. All rights reserved.

Spring Boot Backend Development Course, Implementing Login and Logout with Spring Security, User Registration, Creating a Repository

Hello! In this blog post, we will learn how to develop a backend application using Spring Boot, implement login and logout functionalities with Spring Security, and add a user registration feature. We will also cover how to create repositories for interacting with the database. This course is suitable for everyone from beginners to intermediate learners.

1. What is Spring Boot?

Spring Boot is a framework that helps develop applications quickly based on the Spring Framework. By using Spring Boot, we can minimize complex configurations and swiftly create microservices or standalone applications. The main features of Spring Boot are:

  • Auto Configuration: Easily configure without complex XML settings through code and annotations.
  • Starters: Use starters that bundle the necessary dependencies for easy dependency management.
  • Ease of Deployment: Easily deployable as a standalone executable JAR file.

2. Setting Up the Project

You can quickly create a Spring Boot project using Spring Initializr. Select the necessary dependencies, create a Maven project, and import it into your IDE. Below is a list of essential dependencies:

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

2.1 Creating the Project with IntelliJ

Let’s look at how to create a project using IntelliJ. First, open IntelliJ and follow these steps:

  1. Select File > New > Project
  2. Select Spring Initializr and click ‘Next’
  3. Enter Group, Artifact, Name, and click ‘Next’
  4. Select necessary dependencies and click ‘Finish’

3. Configuring Spring Security

Spring Security is a powerful framework that is used to add security features to Spring applications. It supports easy implementation of authentication and authorization functionalities. Here, we will implement basic login/logout features.

3.1 Adding Spring Security Dependency

Although this dependency is already included in the dependencies selected from Spring Initializr, you can additionally add the Spring Security dependency in the pom.xml file if needed:


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

3.2 Creating the SecurityConfig Class

To configure Spring Security, we create the `SecurityConfig` class. This class configures the security filter chain for Spring Security:


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("/login", "/register").permitAll() // Allow access to login and registration pages
                .anyRequest().authenticated() // All other requests require authentication
            .and()
            .formLogin()
                .loginPage("/login") // Set login page
                .permitAll() // Allow all users to access
            .and()
            .logout()
                .permitAll(); // Allow logout functionality
    }
}

4. Implementing User Registration

To implement the registration feature, we will create a User entity and UserRepository. Then we will create a service that saves user information to the database.

4.1 Creating the User Entity


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
}

4.2 Creating the UserRepository Interface


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

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);
}

4.3 Implementing the Registration Service

We will create a UserService class to handle user information for registration:


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;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public void registerUser(User user) {
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword); // Encrypt password
        userRepository.save(user); // Save user information
    }
}

4.4 Implementing the Registration Controller

We will create a controller to handle registration requests:


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 UserController {
    @Autowired
    private UserService userService;

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

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

5. Implementing View Templates

In Spring Boot, we mainly use Thymeleaf to create HTML templates. Let’s create view templates for the login and registration pages.

5.1 Login Page


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

5.2 Registration Page


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Registration Page</title>
</head>
<body>
    <h1>Register</h1>
    <form th:action="@{/register}" method="post">
        <div>
            <label>Username:</label>
            <input type="text" name="username" required />
        </div>
        <div>
            <label>Password:</label>
            <input type="password" name="password" required />
        </div>
        <button type="submit">Register</button>
    </form>
    <a th:href="@{/login}">Go to login</a>
</body>
</html>

6. Conclusion

In this post, we learned how to develop a backend application using Spring Boot and how to implement login and registration features through Spring Security. We gained an understanding of the basic usage of Spring Boot and its security features through a simple example. I hope this practical exercise leads to effective learning.

As you proceed with future projects, try implementing more complex features and learning advanced technologies. I wish you to become a developer who continuously learns and grows. Thank you!

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

In this course, we will learn how to develop backend applications using Spring Boot. Specifically, we will implement login/logout functionality and a registration system utilizing Spring Security, as well as cover the necessary content for creating views. Through this course, you will gain an understanding of the basic structure of web applications and their security aspects.

1. Introduction to Spring Boot

Spring Boot is a Java-based framework that provides tools for developing Spring applications quickly and simply. It simplifies the complex configurations often encountered in traditional Spring development, allowing developers to focus on business logic.

1.1 Advantages of Spring Boot

  • Auto-configuration: Spring Boot automatically configures the necessary settings when running the application.
  • Standalone: Spring Boot applications can run independently, including an embedded Tomcat server.
  • Convenient dependency management: Library dependencies can be easily managed via Maven or Gradle.

2. Setting Up Security with Spring Security

Spring Security provides robust authentication and authorization features for securing Spring-based applications. In this section, we will learn how to configure Spring Security and implement login and logout functionality.

2.1 Adding Dependencies

To use Spring Security, add the following dependencies to the build.gradle file:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    runtimeOnly 'com.h2database:h2'
}

2.2 Creating the Spring Security Configuration Class

We will create a SecurityConfig class for Spring Security configuration. The code below includes basic login and logout settings:

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").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

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

3. Implementing Registration Functionality

To implement the registration functionality, we will create an entity to store user information and a repository for database integration. After that, we will create a controller to handle the registration process.

3.1 Creating the User Entity

We will write a User class to store user information:

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;

    // getters and setters
}

3.2 Creating the UserRepository

We will create a repository to manage User information using JPA:

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

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

3.3 Creating Registration Form and Controller

We will create an HTML form for registration and a controller to handle it. We will create a RegisterController to process registration requests:

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.RequestMapping;

@Controller
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private UserRepository userRepository;

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

    @PostMapping
    public String registerUser(User user) {
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        userRepository.save(user);
        return "redirect:/login";
    }
}

3.4 Creating Registration HTML Form

We will create a form for registration:





    Registration


    

Registration




4. Implementing Login/Logout Functionality

We will implement the login and logout functionality to allow users to securely access the system.

4.1 Creating Login HTML Form

We will create the login form:





    Login


    

Login



4.2 Handling Logout

The logout functionality is provided by Spring Security by default, specifying a logout URL through which logout is processed. It uses the default /logout path.

5. Creating Views

Now that we have implemented the registration and login functionality, we will create the views that will be displayed to the users. When using Spring Boot, we mainly use a template engine called Thymeleaf.

5.1 Setting Up Thymeleaf

To use Thymeleaf, add the following dependency to the build.gradle file:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}

5.2 Creating a Basic Home Page

We will create a controller and view to display the home page. Below is the HTML code representing the home page:





    Home


    

Home Page

Hello, User! Logout

Login
Register

6. Conclusion

In this way, we have built a web application with simple registration and login/logout functionality using Spring Boot. Through this project, you will understand the basic usage of Spring Boot and implementing security features using Spring Security.

6.1 Next Steps

You can now consider adding more complex features or developing a RESTful API to communicate with the frontend. It is also good to think about integration with mobile applications or other clients. If necessary, integrating external authentication services like OAuth2 is also a good direction.

6.2 Additional Resources

If you want more information, please refer to the official Spring Boot documentation and Spring Security documentation:

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