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!