1. Introduction
In modern web applications, there are various methods to efficiently perform user authentication and authorization management. Among these, JSON Web Token (JWT) is one of the widely used authentication methods. In particular, for backend developers using Spring Boot, JWT can be used to implement login and logout functionalities to create a safer and more efficient user authentication system. This course will explain in detail the concept of JWT, how to implement JWT-based authentication using Spring Boot, and the procedures for login and logout.
2. What is JWT?
JWT stands for JSON Web Token, which is an open standard (RFC 7519) for securely transmitting information between the user and the server. JWT is typically used in the following cases:
- User authentication
- Information exchange
- Authorization
The characteristics of JWT are as follows:
- It can carry information by itself.
- It can prevent tampering using a signature.
- It can be easily used in HTTP transmissions.
JWT consists of three parts: Header, Payload, and Signature. Detailed explanations of each part are as follows.
2.1 Header
The header of a JWT contains two pieces of information: the type of the token and the algorithm used (e.g., HMAC SHA256 or RSA).
{
"alg": "HS256",
"typ": "JWT"
}
2.2 Payload
The payload is the second part of the JWT that contains information about the user and claims. Claims can include user information, permissions, and other metadata. For example:
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
In this example, “sub” represents the user’s unique ID, “name” represents the username, and “iat” indicates the time issued.
2.3 Signature
Lastly, the signature is created by combining the header and payload and generating a hash using a secret key. This allows the integrity of the data to be verified. For example:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
Through this process, a JWT is generated, and the recipient can verify the validity of the token using the secret key they possess.
3. Spring Boot Setup
To implement a JWT-based user authentication system using Spring Boot, you first need to set up a Spring Boot project. You should create a new project using Spring Initializr and add the necessary dependencies. In this course, we will use Spring Web, Spring Security, and the jjwt library.
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'io.jsonwebtoken:jjwt:0.9.1'
}
4. Configuring Spring Security and JWT
You can set up basic authentication and authorization using Spring Security. To do this, you need to write a SecurityConfig class and define security rules for HTTP requests.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
In the above configuration, the /api/auth/** route is allowed for all requests, while other requests require authentication. The session management is set to STATLESS to utilize token-based authentication using JWT.
5. User Authentication and JWT Issuance
When a user logs in, the server issues a JWT based on the user’s information. You need to write an AuthController class for user authentication and implement a method to handle login requests.
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtProvider jwtProvider;
@PostMapping("/login")
public ResponseEntity> authenticateUser(@RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtProvider.generateToken(authentication);
return ResponseEntity.ok(new JwtResponse(jwt));
}
}
6. Implementing Logout
Since JWT does not store state values on the server, implementing logout works differently than other methods. Generally, logout is handled by deleting or expiring the JWT on the client side. For example, when the client sends a logout request, the JWT token is deleted, and this token is no longer used for subsequent requests.
@PostMapping("/logout")
public ResponseEntity> logoutUser() {
// Response handling for client token deletion
return ResponseEntity.ok(new MessageResponse("User logged out successfully!"));
}
7. JWT Validation
To validate a JWT on the server, the signature of the token is checked, and the expiration is verified. A JwtProvider can be written for this process.
@Component
public class JwtProvider {
@Value("${jwt.secret}")
private String jwtSecret;
public String generateToken(Authentication authentication) {
return Jwts.builder()
.setSubject(authentication.getName())
.setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + 86400000)) // 1 day
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
}
8. Conclusion
We have seen how to efficiently implement user authentication in Spring Boot using JWT. This token-based authentication method allows for a more flexible application structure without maintaining the server’s state. Based on the content explained in this course, I encourage you to implement a user authentication system using JWT in your projects.
In the future, we will provide you with useful information and courses on various web development topics. Thank you.