Xác thực người dùng với Spring Security và JWT
Xác thực người dùng với Spring Security và JWT
Trong bài viết này, chúng ta sẽ xây dựng một hệ thống xác thực người dùng bằng Spring Security kết hợp với JSON Web Token (JWT) – một kỹ thuật phổ biến để bảo vệ REST API.
💡 Ý tưởng
- Người dùng đăng nhập bằng email/password → nhận JWT token.
- Gửi JWT ở mỗi request → xác thực & cho phép truy cập tài nguyên bảo vệ.
🔐 Cấu hình Security
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.csrf().disable()
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/**").permitAll()
.anyRequest().authenticated())
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class)
.build();
}
}
🛠️ JWT Utility
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Component
public class JwtUtil {
private final String SECRET = "secret_key";
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 1 ngày
.signWith(SignatureAlgorithm.HS256, SECRET)
.compact();
}
public String extractUsername(String token) {
return Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody()
.getSubject();
}
}
✅ Đăng nhập
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired
private JwtUtil jwtUtil;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest request) {
// Xác thực user (ví dụ hardcoded)
if ("admin".equals(request.getUsername()) && "123456".equals(request.getPassword())) {
String token = jwtUtil.generateToken(request.getUsername());
return ResponseEntity.ok(new JwtResponse(token));
}
return ResponseEntity.status(401).body("Unauthorized");
}
}
🧾 Kết luận
Trên đây là cách triển khai xác thực người dùng với Spring Security và JWT trong một ứng dụng Spring Boot. Giải pháp này giúp bảo vệ REST API hiệu quả và dễ mở rộng.
Trong các bài viết tiếp theo, mình sẽ chia sẻ:
- Cách tích hợp JWT với cơ sở dữ liệu thực tế
- Cách sử dụng refresh token
- Phân quyền truy cập theo vai trò (ROLE)
Cảm ơn bạn đã đọc đến đây! Nếu thấy hữu ích, đừng ngại chia sẻ hoặc góp ý bên dưới. Chúc bạn thành công! 🙌
This post is licensed under CC BY 4.0 by the author.