1. Introduction
Security is one of the most important factors in modern web applications. User authentication and authorization are key functions in maintaining this security.
In this course, we will take a detailed look at how to implement login and logout features using JWT (JSON Web Token) in backend development with Spring Boot.
This course covers the process of setting up a basic Spring Boot application, implementing a JWT-based authentication system, and adding a controller to complete the RESTful API.
2. What is Spring Boot?
Spring Boot is a tool that makes it easier to use the Java-based framework Spring.
This allows developers to minimize configuration and setup, enabling rapid application development.
Spring Boot can be packaged into a standalone JAR file and can efficiently develop RESTful services.
The main features of Spring Boot are as follows:
- Auto-configuration: Spring Boot automatically configures the basic settings needed by developers.
- Starter packages: Developers can use starter packages to quickly add the functionality they need.
- Embedded server: Spring Boot provides embedded servers such as Tomcat, Jetty, and Undertow, making it easy to run applications.
- Dependency management: Dependencies can be easily managed within the source code using Maven or Gradle.
3. What is JWT?
JWT (JSON Web Token) is an Internet standard RFC 7519 for secure information transmission. JWT uses a JSON object to encrypt and convey information such as subject (sub), issuer (iss), and expiration time (exp).
JWT is composed of three parts:
- Header: Specifies the type of JWT and the signing algorithm used.
- Payload: Contains the information to be transmitted and metadata describing that information.
- Signature: Secures the header and payload to prevent tampering. It is created using a secret key.
JWT is widely used for API authentication in high-traffic environments. It is efficient as there is no need to store sessions on the server, and it allows the client to hold state information,
reducing the load on the server.
4. Project Setup
4.1. Creating a Spring Boot Project
We use Spring Initializr to create a Spring Boot project.
Enter the necessary configurations as follows:
- Project: Maven Project
- Language: Java
- Spring Boot: 2.6.6 (latest version)
- Project Metadata:
- Group: com.example
- Artifact: jwt-demo
- Name: jwt-demo
- Description: JWT Authentication Demo
- Packaging: Jar
- Java: 11
Then, add the following dependencies:
- Spring Web
- Spring Security
- Spring Data JPA
- H2 Database
- jjwt (Java JWT)
4.2. Project Structure
After creating the project, the basic package structure will be as follows:
└── src └── main ├── java │ └── com │ └── example │ └── jwt_demo │ ├── JwtDemoApplication.java │ ├── controller │ ├── model │ ├── repository │ ├── security │ └── service └── resources ├── application.properties └── static
5. Database Configuration
We can use the H2 database to store user information.
Configure the application.properties file as follows:
spring.h2.console.enabled=true spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
6. Creating a User Model
We create a User model class to hold user information.
package com.example.jwt_demo.model; import javax.persistence.*; @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, unique = true) private String username; @Column(nullable = false) private String password; // Getters and Setters... public User() {} public User(String username, String password) { this.username = username; this.password = password; } }
7. Creating a User Repository
We create a JPA repository interface to manage user information in the database.
package com.example.jwt_demo.repository; import com.example.jwt_demo.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository{ User findByUsername(String username); }
8. Security Configuration
We will implement JWT authentication through Spring Security. To do this, we create a SecurityConfig class that extends WebSecurityConfigurerAdapter.
package com.example.jwt_demo.security; import com.example.jwt_demo.filter.JwtRequestFilter; import com.example.jwt_demo.service.UserDetailsServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.AuthenticationManager; 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.config.http.SessionCreationPolicy; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsServiceImpl userDetailsService; @Autowired private JwtRequestFilter jwtRequestFilter; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/authenticate").permitAll() .anyRequest().