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:
- Select File > New > Project
- Select Spring Initializr and click ‘Next’
- Enter Group, Artifact, Name, and click ‘Next’
- 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!