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!