This course covers the basics of backend development using Spring Boot and explains how to implement login, logout, and user registration functionalities through Spring Security.
1. What is Spring Boot?
Spring Boot is an application framework based on the Spring Framework that helps developers set up and run Spring applications more easily. It minimizes the complex setup process and provides an embedded server, allowing developers to quickly build applications. Its main features include:
- Auto Configuration: Developers can run their applications using default values without having to write configuration files.
- Dependency Management: Required libraries can be easily added through Maven or Gradle.
- Control over Dependencies: You can pin specific versions of libraries.
2. Creating a Project
There are various ways to create a new project using Spring Boot, but the easiest way to get started is to use Spring Initializr. Let’s follow the steps below to create a project.
- Access Spring Initializr
- Select Project: Maven Project
- Select Language: Java
- Select Spring Boot: Latest Version
- Input Group: com.example
- Input Artifact: demo
- Select Dependencies: Spring Web, Spring Security, Spring Data JPA, H2 Database
- Click Generate to download the ZIP file
3. Understanding Project Structure
When you open the generated project, you can see the following main directory and file structure.
├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ ├── DemoApplication.java │ │ │ └── configuration │ │ │ └── SecurityConfig.java │ │ └── resources │ │ ├── application.properties │ │ └── static │ └── test ├── pom.xml
Here, the DemoApplication.java
file is the main application file, and application.properties
is the configuration file.
4. Adding Dependencies
The project we created includes the necessary libraries as Maven dependencies. Let’s open the pom.xml
file to check the added dependencies.
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <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> </dependencies>
5. Implementing Registration Functionality
To allow users to register, we need to save and manage user information. For this purpose, we will create a user entity using JPA and set up the connection to the database.
5.1 Creating the User Entity
First, let’s create an entity class called User
. This class holds user information.
package com.example.demo.model; import javax.persistence.*; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; private String email; // Getters and Setters }
5.2 Creating UserRepository
Now, we will create a UserRepository
interface to save and retrieve user information from the database.
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 Writing the Registration Service
We will write a service class to handle the 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.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; public User registerNewUser(User user) { return userRepository.save(user); } }
6. Configuring Spring Security
Now we will set up Spring Security to implement login and logout functionalities.
6.1 Creating SecurityConfig Class
We will create a class for security configuration.
package com.example.demo.configuration; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; 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; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService); } @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(); } }
7. Implementing Registration and Login Controllers
We will write a controller to handle registration and login functionalities.
7.1 Creating AuthController Class
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.registerNewUser(user); return "redirect:/login"; } @GetMapping("/login") public String login() { return "login"; } }
8. Creating Login/Logout Pages
Now we will create the login and registration pages. Create login.html
and register.html
files under the src/main/resources/templates
folder.
8.1 register.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>User Registration</title> </head> <body> <h1>User Registration</h1> <form action="/register" method="post"> <label>Username: </label><input type="text" name="username"><br> <label>Password: </label><input type="password" name="password"><br> <label>Email: </label><input type="email" name="email"><br> <input type="submit" value="Register"> </form> </body> </html>
8.2 login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <h1>Login</h1> <form action="/login" method="post"> <label>Username: </label><input type="text" name="username"><br> <label>Password: </label><input type="password" name="password"><br> <input type="submit" value="Login"> </form> </body> </html>
9. Running the Application
Now that all configurations are complete, enter the following command in the terminal to run the application.
mvn spring-boot:run
Open your browser and navigate to http://localhost:8080/register
to proceed with the registration. You can then access the application by logging in.
10. Conclusion and Next Steps
In this course, we learned how to build a backend application using Spring Boot and implement basic login and registration functionalities with Spring Security. Now you can build upon this basic structure to add various features such as API token-based authentication and OAuth2 integration.
Suggested Next Steps
- Implement API REST
- Add JWT (JSON Web Token) based authentication
- Enhance authentication with OAuth2
- Create a complete application with frontend integration
Make great use of what you learned in this course to create fantastic projects!