Sécurisation d’une API Spring Boot
avec JWT
Réalisé par : Anouar Ouhssain, Zakaria Naji, Hossam Tabsissi, Amine Elhend,
Ayman Ait Abdou, Yassir Aboulcaid, Hassani Mohammed, Zakaria Syabri,
Mouad Boulaid, Mohamed Ouhadda, Badr Elhot, Jalaledinne El Firqi
Année universitaire 2024-2025
Figure 1 – Structure d’un JWT
TP Spring Boot & JWT 2
Table des matières
Introduction 3
1 Présentation générale 3
2 Étape 1 : Création du projet Spring Boot 3
3 Étape 2 : Création de l’entité Utilisateur 3
4 Étape 3 : Configuration de JWT 4
5 Étape 4 : Sécurité avec Spring Security 6
6 Étape 5 : Authentification utilisateur 6
7 Étape 6 : Test avec Postman 7
Conclusion 7
TP Spring Boot & JWT 3
Introduction
Dans un monde connecté, les applications doivent garantir la confidentialité et la sécurité
des utilisateurs. Ce TP vous apprend à créer une API REST sécurisée grâce à Spring Boot,
Spring Security et les JSON Web Tokens (JWT). Il vous accompagnera étape par étape, depuis
la création du projet jusqu’à sa sécurisation et sa mise à l’épreuve avec Postman.
1 Présentation générale
Objectifs pédagogiques
— Comprendre le principe d’authentification par JWT.
— Concevoir une application sécurisée avec Spring Boot 3.
— Séparer les couches de logique métier, persistance, et sécurité.
— Maîtriser les tests avec Postman.
Outils nécessaires
— JDK 17+ : https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads
html
— Maven : https://maven.apache.org/download.cgi
— IDE : IntelliJ IDEA Community (recommandé) ou VS Code
— Postman : pour tester les endpoints HTTP
2 Étape 1 : Création du projet Spring Boot
1. Allez sur https://start.spring.io
2. Sélectionnez :
— Project : Maven
— Language : Java
— Spring Boot : 3.3.x
— Group : com.example
— Artifact : jwtapp
3. Cliquez sur "Add Dependencies" et ajoutez :
— Spring Web
— Spring Security
— Spring Data JPA
— Lombok
— H2 Database
4. Générez le projet et ouvrez-le avec IntelliJ.
3 Étape 2 : Création de l’entité Utilisateur
2.1 Classe User.java
TP Spring Boot & JWT 4
1 @Entity
2 @Data
3 @NoArgsConstructor
4 @AllArgsConstructor
5 public class User {
6 @Id @GeneratedValue
7 private Long id ;
8 private String username ;
9 private String password ;
10 private String role ;
11 }
2.2 Interface UserRepository.java
1 public interface UserRepository extends JpaRepository < User , Long > {
2 Optional < User > findByUsername ( String username ) ;
3 }
4 Étape 3 : Configuration de JWT
3.1 Ajouter les dépendances dans pom.xml
1 < dependency >
2 < groupId > io . jsonwebtoken </ groupId >
3 < artifactId > jjwt - api </ artifactId >
4 < version >0.11.5 </ version >
5 </ dependency >
6 < dependency >
7 < groupId > io . jsonwebtoken </ groupId >
8 < artifactId > jjwt - impl </ artifactId >
9 < version >0.11.5 </ version >
10 < scope > runtime </ scope >
11 </ dependency >
12 < dependency >
13 < groupId > io . jsonwebtoken </ groupId >
14 < artifactId > jjwt - jackson </ artifactId >
15 < version >0.11.5 </ version >
16 < scope > runtime </ scope >
17 </ dependency >
3.2 Service JwtService.java
1 @Service
2 public class JwtService {
3 private final String SECRET = " secret - key " ;
4
TP Spring Boot & JWT 5
5 public String generateToken ( UserDetails userDetails ) {
6 return Jwts . builder ()
7 . setSubject ( userDetails . getUsername () )
8 . setIssuedAt ( new Date () )
9 . setExpiration ( new Date ( System . currentTimeMillis () + 3600000)
)
10 . signWith ( SignatureAlgorithm . HS256 , SECRET )
11 . compact () ;
12 }
13
14 public String extractUsername ( String token ) {
15 return Jwts . parser () . setSigningKey ( SECRET )
16 . parseClaimsJws ( token ) . getBody () . getSubject () ;
17 }
18 }
3.3 Filtre JwtAuthFilter.java
1 @Component
2 public class JwtAuthFilter extends OncePerRequestFilter {
3 @Autowired JwtService jwtService ;
4 @Autowired UserDetailsService userDetailsService ;
5
6 @Override
7 protected void doFilterInternal ( HttpServletRequest req ,
HttpServletResponse res , FilterChain chain ) throws ... {
8 final String auth = req . getHeader ( " Authorization " ) ;
9 if ( auth == null || ! auth . startsWith ( " Bearer " ) ) {
10 chain . doFilter ( req , res ) ;
11 return ;
12 }
13 String token = auth . substring (7) ;
14 String username = jwtService . extractUsername ( token ) ;
15
16 if ( username != null && SecurityContextHolder . getContext () .
getAuthentication () == null ) {
17 UserDetails userDetails = userDetailsService .
loadUserByUsername ( username ) ;
18 U se r n a m e P a s s w o r d A u t h e n t i c a t i o n T o k e n authToken =
19 new U s e r n a m e P a s s w o r d A u t h e n t i c a t i o n T o k e n ( userDetails , null ,
userDetails . getAuthorities () ) ;
20 SecurityContextHolder . getContext () . setAuthentication (
authToken ) ;
21 }
22 chain . doFilter ( req , res ) ;
23 }
24 }
TP Spring Boot & JWT 6
5 Étape 4 : Sécurité avec Spring Security
SecurityConfig.java
1 @Configuration
2 @EnableWebSecurity
3 public class SecurityConfig {
4 @Autowired JwtAuthFilter jwtAuthFilter ;
5
6 @Bean
7 public SecurityFilterChain securityFilterChain ( HttpSecurity http )
throws Exception {
8 http . csrf () . disable ()
9 . authorizeHttpRequests ()
10 . requestMatchers ( " / api / auth /** " ) . permitAll ()
11 . anyRequest () . authenticated ()
12 . and ()
13 . sessionManagement () . sessionCreationPolicy (
SessionCreationPolicy . STATELESS ) ;
14
15 http . addFilterBefore ( jwtAuthFilter ,
U s e r n a m e P a s s w o r d A u t h e n t i c a t i o n F i l t e r . class ) ;
16 return http . build () ;
17 }
18 }
6 Étape 5 : Authentification utilisateur
AuthController.java
1 @RestController
2 @RequestMapping ( " / api / auth " )
3 public class AuthController {
4 @Autowired AuthenticationManager authManager ;
5 @Autowired JwtService jwtService ;
6 @Autowired UserRepository repo ;
7
8 @PostMapping ( " / login " )
9 public String login ( @RequestBody AuthRequest req ) {
10 authManager . authenticate (
11 new U s e r n a m e P a s s w o r d A u t h e n t i c a t i o n T o k e n ( req . getUsername () ,
req . getPassword () ) ) ;
12 return jwtService . generateToken ( repo . findByUsername ( req .
getUsername () ) . get () ) ;
13 }
14 }
TP Spring Boot & JWT 7
7 Étape 6 : Test avec Postman
1. Endpoint : POST /api/auth/login
2. Body JSON :
1 {
2 " username " : " admin " ,
3 " password " : " 1234 "
4 }
3. Copier le token retourné.
4. Ajouter dans les headers de requête : Authorization: Bearer VOTRE_TOKEN
5. Appeler un endpoint sécurisé /api/user/data
Conclusion
Ce TP vous a permis de mettre en œuvre une architecture sécurisée avec Spring Boot
3. Vous maîtrisez maintenant la base d’un système d’authentification moderne sans session,
facile à intégrer dans des projets plus complexes.