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
- Overview of Spring Boot
- Introduction to Spring Security
- Project Setup
- Implementing Membership Registration
- Implementing Login and Logout
- Adding Logout Method
- 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!