0% ont trouvé ce document utile (0 vote)
137 vues55 pages

Cours Spring Boot JWT

Transféré par

ekoue andreas
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
137 vues55 pages

Cours Spring Boot JWT

Transféré par

ekoue andreas
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

JWT et Spring Boot

Achref El Mouelhi

Docteur de l’université d’Aix-Marseille


Chercheur en programmation par contrainte (IA)
Ingénieur en génie logiciel

[Link]@[Link]

H & H: Research and Training 1 / 47


Plan

1 JWT

2 Intégration de Spring Security

3 Intégration de JWT

H & H: Research and Training 2 / 47


JWT

Spring Boot

JWT : JSON Web Token

Librairie d’échange sécurisé d’informations

Utilisant des algorithmes de cryptage comme HMAC SHA256 ou RSA

H I ©
EL
Utilisant les jetons (tokens)

O U
LM
Un jeton est composé de trois parties séparées par un point :

f E
entête (header) : objet JSON décrivant le jeton encodé en base 64
r e
ch
charge utile (payload) : objet JSON contenant les informations du jeton encodé en

©A
base 64

Une signature numérique = concaténation de deux éléments précédents séparés


par un point + une clé secrète (le tout crypté par l’algorithme spécifié dans l’entête)

Documentation officielle : [Link]

H & H: Research and Training 3 / 47


JWT

Spring Boot
Entête : exemple
{
"alg": "HS256",
"typ": "JWT"
H I ©
EL
}

O U
f ELM
ch r e
©A

H & H: Research and Training 4 / 47


JWT

Spring Boot
Entête : exemple
{
"alg": "HS256",
"typ": "JWT"
H I ©
EL
}

O U
f ELM
Charge utile : exemple
ch r e
{
© A
"sub": "1234567890",
"name": "John Doe",
"admin": true
}

H & H: Research and Training 4 / 47


JWT

Spring Boot
Exemple de construction de signature en utilisant l’algorithme précisé dans l’entête
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)

H I ©
U EL
O
f E LM
ch r e
©A

H & H: Research and Training 5 / 47


JWT

Spring Boot
Exemple de construction de signature en utilisant l’algorithme précisé dans l’entête
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)

H I ©
Résultat
U EL
O
f E LM
ch r e
©A

H & H: Research and Training 5 / 47


JWT

Spring Boot
Exemple complet (pour tester [Link]

H I ©
UEL
O
f ELM
ch r e
©A

H & H: Research and Training 6 / 47


JWT

Spring Boot

H I ©
EL
Pour décoder les deux premières parties d’un jeton
U
O
[Link]
f ELM
ch r e
©A

H & H: Research and Training 7 / 47


Intégration de Spring Security

Spring Boot

Objectif

Sécuriser l’accès à nos ressources REST en minimisant l’accès à la


base de données pour vérifier l’identité de l’utilisateur.
H I ©
UEL
O
f E LM
ch r e
©A

H & H: Research and Training 8 / 47


Intégration de Spring Security

Spring Boot

Objectif

Sécuriser l’accès à nos ressources REST en minimisant l’accès à la


base de données pour vérifier l’identité de l’utilisateur.
H I ©
UEL
O
f E LM
Ce qu’il faut
ch r e
©A
Spring Security pour la gestion des utilisateurs
JWT pour les jetons

H & H: Research and Training 8 / 47


Intégration de Spring Security

Spring Boot
Création de projet Spring Boot

Aller dans File > New > Other

Chercher Spring, dans Spring Boot sélectionner Spring Starter Project et


cliquer sur Next >

H I ©
Saisir
UEL
spring-boot-jwt dans Name,
O
[Link] dans Group,
f E LM
ch r e
spring-boot-jwt dans Artifact

©A
[Link] dans Package

Cliquer sur Next

Chercher et cocher les cases correspondantes aux Spring Data JPA, MySQL Driver,
Spring Web, Spring Boot DevTools, Lombok et Spring Security

Cliquer sur Next puis sur Finish

H & H: Research and Training 9 / 47


Intégration de Spring Security

Spring Boot

Explication

Le package contenant le point d’entrée de notre application (la classe contenant le


puclic static void main) est [Link]

H I ©
EL
Tous les autres packages dao, model... doivent être dans le package demo.

O U
f E LM
ch r e
©A

H & H: Research and Training 10 / 47


Intégration de Spring Security

Spring Boot

Explication

Le package contenant le point d’entrée de notre application (la classe contenant le


puclic static void main) est [Link]

H I ©
EL
Tous les autres packages dao, model... doivent être dans le package demo.

O U
f E LM
Pour la suite, nous considérons
ch r e
©A
une entité Personne à définir dans [Link]

une interface DAO PersonneRepository à définir dans [Link]

un contrôleur REST PersonneController à définir dans [Link]

H & H: Research and Training 10 / 47


Intégration de Spring Security

Spring Boot

Dans [Link], ajoutons les données permettant la connexion à la base de données et la


configuration de Hibernate

[Link] = jdbc:mysql://localhost:3306/cours_boot?createDatabaseIfNotExist
=true
[Link] = root
H I ©
EL
[Link] = root
[Link]-auto = update
[Link]-sql = true
O U
LM
[Link] = [Link]
[Link]-strategy = [Link].
PhysicalNamingStrategyStandardImpl

r e f E
ch
©A
L’ajout de la propriété [Link]-strategy permet de forcer Hibernate à
utiliser les mêmes noms pour les tables et les colonnes que les entités et les attributs.

H & H: Research and Training 11 / 47


Intégration de Spring Security

Spring Boot

Lancez l’application et vérifiez la génération d’un mot de passe dans la


console
Using generated security password : 895a8a45-d296-4ee6-a246- H I ©
421d6dd6e64e UEL
O
f E LM
ch r e
©A

H & H: Research and Training 12 / 47


Intégration de Spring Security

Spring Boot

Lancez l’application et vérifiez la génération d’un mot de passe dans la


console
Using generated security password : 895a8a45-d296-4ee6-a246- H I ©
421d6dd6e64e UEL
O
f E LM
ch r e
Remarque ©A
Ce mot de passe est à utiliser pour accéder aux ressources.

H & H: Research and Training 12 / 47


Intégration de Spring Security

Spring Boot

Pour tester
H I ©
Il faut aller à [Link]
U EetLvérifiez l’affichage
de l’interface d’authentification
L MO
Utilisez user comme nom
r e f Ed’utilisateur et le mot de passé généré
et affiché dansc lah
console pour la connexion
© A

H & H: Research and Training 13 / 47


Intégration de Spring Security

Créons une entité Personne dans [Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
H I ©
EL
import [Link];
import [Link];
O U
@NoArgsConstructor
@AllArgsConstructor
f E LM
@Data
ch r e
©A
@Entity
public class Personne {
@Id
@GeneratedValue(strategy = [Link])
private Long num;
private String nom;
private String prenom;
}

H & H: Research and Training 14 / 47


Intégration de Spring Security

Spring Boot & REST

Préparons notre interface DAO PersonneRepository

package [Link];
H I ©
import [Link];
UEL
O
LM
import [Link];

f E
public interface PersonneRepository extends JpaRepository<Personne, Long> {

r e
}
ch
©A

H & H: Research and Training 15 / 47


Intégration de Spring Security

Spring Boot
Créons le contrôleur REST suivant dans [Link]

@RestController
public class PersonneRestController {

@Autowired
private PersonneRepository personneRepository;

H I ©
EL
@GetMapping("/personnes")
public List<Personne> getPersonnes() {
O U
LM
return [Link]();
}

r e f E
ch
@GetMapping("/personnes/{id}")

©A
public Personne getPersonne(@PathVariable("id") long id) {
return [Link](id).orElse(null);
}

@PostMapping("/personnes")
public Personne addPersonne(@RequestBody Personne personne) {
return [Link](personne);
}
}

H & H: Research and Training 16 / 47


Intégration de Spring Security

Spring Boot

H I ©
EL
Pour tester
Il faut aller à [Link] ou sur http:O U
//localhost:8080/personnes/1.
f E LM
ch r e
©A

H & H: Research and Training 17 / 47


Intégration de Spring Security

Spring Boot

Dans [Link], définissons la classe SecurityConfig

package [Link];

H I ©
EL
import [Link];

U
import [Link]
O
LM
.EnableWebSecurity;

@Configuration
r e f E
ch
@EnableWebSecurity

©A
public class SecurityConfig {

H & H: Research and Training 18 / 47


Intégration de Spring Security

Spring Boot
Contenu de SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
private UserDetailsService userDetailsService;

@Bean
public static NoOpPasswordEncoder passwordEncoder() {
H I ©
EL
return (NoOpPasswordEncoder) [Link]();
}

O U
LM
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http,

throws Exception {
r e E
NoOpPasswordEncoder noOpPasswordEncoder, UserDetailsService userDetailService)
f
ch
return [Link]([Link])

©A
.userDetailsService(userDetailsService)
.passwordEncoder(noOpPasswordEncoder)
.and().build();
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return [Link]().disable().authorizeHttpRequests((authz) -> [Link]
().authenticated())
.httpBasic([Link]()).build();
}
}

H & H: Research and Training 19 / 47


Intégration de Spring Security

Spring Boot

Contenu de l’entité Role


@NoArgsConstructor
@AllArgsConstructor
H I ©
EL
@Data
@Entity
O U
LM
public class Role {

@Id
r e f E
ch
©A
@GeneratedValue(strategy = [Link])
Long id;
String titre;
}

H & H: Research and Training 20 / 47


Intégration de Spring Security

Spring Boot
Contenu de l’entité User

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
public class User {
@Id
H I ©
@GeneratedValue(strategy = [Link])
UEL
Long num;
O
LM
String username;
String password;

r e f E
@ManyToMany(cascade = { [Link], [Link] },
fetch = [Link])
ch
}
List<Role> roles;
©A

fetch = [Link] : les Role seront chargés au même temps que les User.

H & H: Research and Training 21 / 47


Intégration de Spring Security

Spring Boot

Contenu de UserRepository

public interface UserRepository extends JpaRepository<User, Long> {

}
public User findByUsername(String username);

H I ©
UEL
La méthode findByUsername sera utilisée plus tard.
O
f E LM
ch r e
©A

H & H: Research and Training 22 / 47


Intégration de Spring Security

Spring Boot

Contenu de UserRepository

public interface UserRepository extends JpaRepository<User, Long> {

}
public User findByUsername(String username);

H I ©
UEL
La méthode findByUsername sera utilisée plus tard.
O
f E LM
Contenu de RoleRepository
ch r e
©A
public interface RoleRepository extends JpaRepository<Role, Long> {

H & H: Research and Training 22 / 47


Intégration de Spring Security

Spring Boot
Créons une classe qui implémente l’interface UserDetailsService

package [Link];

import [Link];

@Service
H I ©
EL
public class UserDetailsServiceImpl implements UserDetailsService {

}
O U
f E LM
ch r e
©A
Cette classe implémente l’interface UserDetailsService et doit donc implémenter la
méthode loadUserByUserName() qui retourne un objet de type UserDetails
(interface).

L’annotation Service nous permettra d’utiliser cette classe en faisant une injection de
dépendance.

H & H: Research and Training 23 / 47


Intégration de Spring Security

Spring Boot
Contenu de la classe qui implémente UserDetailsService

package [Link];

import [Link];
import [Link];
import [Link];
import
import
[Link];
[Link];
H I ©
EL
import [Link];

@Service
O U
LM
public class UserDetailsServiceImpl implements UserDetailsService {

@Override
r e f E
@Autowired UserRepository userRepository;

ch
©A
public UserDetailsImpl loadUserByUsername(String username) throws
UsernameNotFoundException {
User user = [Link](username);
if (null == user){
throw new UsernameNotFoundException("No user named " + username);
} else {
return new UserDetailsImpl(user);
}
}
}

H & H: Research and Training 24 / 47


Intégration de Spring Security

Spring Boot

Créons une classe qui implémente l’interface UserDetails

package [Link];

H I ©
EL
public class UserDetailsImpl implements UserDetails {

O U
LM
}

r e f E
ch
©A
Cette classe implémente l’interface UserDetails et doit donc implémenter toutes
ses méthodes abstraites

H & H: Research and Training 25 / 47


Intégration de Spring Security

Spring Boot
Créer une classe qui implémente l’interface UserDetails

package [Link];

import [Link];
import [Link];
import [Link];

©
import [Link];
import
I
[Link];

H
EL
import [Link];
import [Link];
import [Link];

O U
LM
public class UserDetailsImpl implements UserDetails {

private User user;

r e f E
ch
public UserDetailsImpl(User user){

©A
[Link] = user;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (final Role role: [Link]())
[Link](new SimpleGrantedAuthority([Link]()));
return authorities;
}

H & H: Research and Training 26 / 47


Intégration de Spring Security

Spring Boot
UserDetailsImpl (la suite)

@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
H I ©
EL
}

U
@Override
public boolean isCredentialsNonExpired() {
O
LM
return true;
}
@Override
public boolean isEnabled() {
r e f E
ch
return true;

©A
}
@Override
public String getUsername() {
return [Link]();
}
@Override
public String getPassword() {
return [Link]();
}
}

H & H: Research and Training 27 / 47


Intégration de Spring Security

Spring Boot

Avant de tester, lancez le projet pour que Spring crée les tables
ensuite créez trois utilisateurs avec des rôles différents
INSERT INTO role VALUES (1, "ROLE_ADMIN"),
(2, "ROLE_USER");
H I ©
UEL
INSERT INTO user VALUES (1, "wick", "wick"),
O
(2, "john", "john"),
f E LM
(3, "alan", "alan");
ch r e
©A
INSERT INTO user_roles VALUES (1, 1),
(2, 2),
(1, 2),
(3, 1);

H & H: Research and Training 28 / 47


Intégration de Spring Security

Spring Boot

H I ©
EL
Pour tester

O U
LM
Il faut aller à [Link] s’authentifier

r e f E
avec les identifiants d’un utilisateur de la table user

ch
©A

H & H: Research and Training 29 / 47


Intégration de JWT

Spring Boot
Ajoutons les dépendances pour JWT

<!-- [Link] -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
H I ©
</dependency>
<dependency>
UEL
O
LM
<groupId>[Link]</groupId>

<version>0.11.5</version>
r e E
<artifactId>jjwt-impl</artifactId>
f
<scope>runtime</scope>
ch
©A
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>

H & H: Research and Training 30 / 47


Intégration de JWT

Spring Boot

H I ©
EL
Ajoutons aussi la propriété suivante dans [Link]
U
O
LM
[Link] = uneclesur32octetsuneclesur32octetsuneclesur32octets

r e f E
ch
©A

H & H: Research and Training 31 / 47


Intégration de JWT

Spring Boot

Commençons par définir une classe JwtTokenUtil pour la


génération et la validation du token
H I ©
package [Link];
UEL
O
@Component
f E LM
public class JwtTokenUtil {
ch r e
} ©A

H & H: Research and Training 32 / 47


Intégration de JWT

Spring Boot

Définissons la durée d’un jeton (5 heures par exemple)

package [Link];
H I ©
@Component
UEL
O
LM
public class JwtTokenUtil {

r e f E
public static final long JWT_TOKEN_VALIDITY = 60 * 60;
ch
}
©A

H & H: Research and Training 33 / 47


Intégration de JWT

Spring Boot

Définissons la durée d’un jeton (5 heures par exemple)

package [Link];
H I ©
@Component
UEL
O
LM
public class JwtTokenUtil {

r e f E
public static final long JWT_TOKEN_VALIDITY = 60 * 60;
ch
}
©A

H & H: Research and Training 34 / 47


Intégration de JWT

Spring Boot

Récupérons la propriété [Link] d’[Link]

package [Link];

H I ©
EL
@Component
public class JwtTokenUtil {
O U
L M
re f E
public static final long JWT_TOKEN_VALIDITY = 60 * 60;

c h
@Value("${[Link]}")

© A secret;
private String

H & H: Research and Training 35 / 47


Intégration de JWT

Spring Boot
Décodons et créons une clé avec le secret

private Key getSigningKey() {


byte[] keyBytes = [Link]().decode([Link]);
return [Link](keyBytes);
}

H I ©
UEL
O
f E LM
ch r e
©A

H & H: Research and Training 36 / 47


Intégration de JWT

Spring Boot
Décodons et créons une clé avec le secret

private Key getSigningKey() {


byte[] keyBytes = [Link]().decode([Link]);
return [Link](keyBytes);
}

H I ©
EL
Définissons les méthodes qui permettent la récupération de données depuis un jeton

U
O
LM
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}

r e f E
ch
public Date getExpirationDateFromToken(String token) {

©A
return getClaimFromToken(token, Claims::getExpiration);
}

public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {


final Claims claims = getAllClaimsFromToken(token);
return [Link](claims);
}

private Claims getAllClaimsFromToken(String token) {


return [Link]().setSigningKey(getSigningKey()).build().parseClaimsJws(token).
getBody();
}

H & H: Research and Training 36 / 47


Intégration de JWT

Spring Boot
Définissons les méthodes qui permettent la génération et la validation du token

public String generateToken(UserDetails userDetails) {


Map<String, Object> claims = new HashMap<>();
[Link]("roles", [Link]());
return [Link]().setClaims(claims).setSubject([Link]()).setIssuedAt(
new Date([Link]()))

I ©
.setExpiration(new Date([Link]() + JWT_TOKEN_VALIDITY * 1000))
.signWith(getSigningKey(), SignatureAlgorithm.HS256).compact();
H
}

U EL
O
f E LM
ch r e
©A

H & H: Research and Training 37 / 47


Intégration de JWT

Spring Boot
Définissons les méthodes qui permettent la génération et la validation du token

public String generateToken(UserDetails userDetails) {


Map<String, Object> claims = new HashMap<>();
[Link]("roles", [Link]());
return [Link]().setClaims(claims).setSubject([Link]()).setIssuedAt(
new Date([Link]()))

I ©
.setExpiration(new Date([Link]() + JWT_TOKEN_VALIDITY * 1000))
.signWith(getSigningKey(), SignatureAlgorithm.HS256).compact();
H
}

U EL
O
f E LM
r e
Et aussi celles qui permettent la génération d’un jeton

ch
©A
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return [Link](new Date());
}

public Boolean validateToken(String token, UserDetails userDetails) {


final String username = getUsernameFromToken(token);
return ([Link]([Link]()) && !isTokenExpired(token));
}

H & H: Research and Training 37 / 47


Intégration de JWT

Spring Boot

Définissons une classe filtre qui intercepte l’accès et qui permet


d’autoriser ou interdire l’accès à un utilisateur
package [Link];
H I ©
UEL
import [Link]; O
f E LM
@Component
ch r e
©A
public class JwtFilter {

H & H: Research and Training 38 / 47


Intégration de JWT

Spring Boot
Cette classe doit hériter de OncePerRequestFilter et implémenter sa méthode abstraite doFilterInternal

package [Link];

import [Link];

import [Link];
import [Link];

H I ©
import
import
[Link];
[Link];
U EL
import [Link];
O
LM
import [Link];

@Component

r e f E
public class JwtFilter extends OncePerRequestFilter {

ch
©A
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain filterChain)
throws ServletException, IOException {

[Link](request, response);
}

H & H: Research and Training 39 / 47


Intégration de JWT

Spring Boot

Injectons les dépendances nécessaires pour le filtre

@Component

©
public class JwtFilter extends OncePerRequestFilter {
@Autowired

H I
EL
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserDetailsService userDetailsService;

O U
LM
@Override

e E
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

f
response, FilterChain filterChain)

r
ch
throws ServletException, IOException {

©A
[Link](request, response);
}

H & H: Research and Training 40 / 47


Intégration de JWT
Implémentons maintenant doFilterInternal

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain filterChain) throws ServletException, IOException {

final String requestTokenHeader = [Link]("Authorization");


String username = null;
String jwtToken = null;
if (requestTokenHeader != null && [Link]("Bearer ")) {
jwtToken = [Link](7);

©
try {

I
username = [Link](jwtToken);

H
EL
} catch (IllegalArgumentException e) {
[Link]("Impossible de récupérer le jeton JWT");
} catch (ExpiredJwtException e) {
O
[Link]("Jeton JWT expiré"); U
LM
}
} else {

e f E
[Link]("Il ne s'agit pas d'une authentification Bearer");

r
ch
}
if (username != null && [Link]().getAuthentication() ==

©A
null) {
UserDetails userDetails = [Link](username);
if ([Link](jwtToken, userDetails)) {
var principalUser = new UsernamePasswordAuthenticationToken(userDetails
, null, [Link]());
[Link](new WebAuthenticationDetailsSource().buildDetails(
request));
[Link]().setAuthentication(principalUser);
}
}
[Link](request, response);
}

H & H: Research and Training 41 / 47


Intégration de JWT

Spring Boot

Mettons à jour SecurityConfig pour charger toutes les classes


précédentes
@Configuration
@EnableWebSecurity
H I ©
public class SecurityConfig {
UEL
O
@Autowired
f E LM
r e
private UserDetailsService userDetailsService;
ch
@Autowired ©A
private JwtFilter jwtFilter;

H & H: Research and Training 42 / 47


Intégration de JWT

Spring Boot
Chargeons les deux beans responsables du chargement de données de l’utilisateur

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Autowired
private UserDetailsService userDetailsService;

H I ©
@Autowired
private JwtFilter jwtFilter;
U EL
O
LM
@Bean

}
E
public static NoOpPasswordEncoder passwordEncoder() {

f
return (NoOpPasswordEncoder) [Link]();

r e
ch
©A
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http, NoOpPasswordEncoder
noOpPasswordEncoder, UserDetailsService userDetailService) throws Exception {
return [Link]([Link])
.userDetailsService(userDetailsService)
.passwordEncoder(noOpPasswordEncoder).and().build();
}

H & H: Research and Training 43 / 47


Intégration de JWT

Spring Boot

Et ensuite le bean responsable de charger le filtre

@Bean
H I ©
EL
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

O U
[Link](jwtFilter, [Link]);

LM
[Link]().and().csrf().disable();
[Link]((authz) -> [Link]("/authenticate").permitAll());

[Link]();
r e f E
[Link]((authz) -> [Link]().fullyAuthenticated());

ch
return [Link]();

©A
}

H & H: Research and Training 44 / 47


Intégration de JWT

Et enfin le contrôleur

@RestController
@CrossOrigin
public class JwtAuthenticationController {

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private JwtTokenUtil jwtTokenUtil;

H I ©
EL
@Autowired
private UserDetailsService userDetailsService;

O U
LM
@PostMapping(value = "/authenticate")
public ResponseEntity<?> createAuthenticationToken(@RequestBody User user) {
try {

r e f E
[Link](new UsernamePasswordAuthenticationToken(user.

ch
getUsername(), [Link]()));

©A
final UserDetails userDetails = [Link](user.
getUsername());
final String token = [Link](userDetails);

return [Link](token);
} catch (Exception e) {
[Link]();
}
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
}

H & H: Research and Training 45 / 47


Intégration de JWT

Spring Boot

Pour obtenir le jeton avec Postman

Dans la liste déroulante, choisir POST puis saisir l’URL vers notre web service
[Link]

H I ©
Dans le Headers, saisir Content-Type comme Key et application/json
comme Value
U EL
O
f E LM
Ensuite cliquer sur Body, cocher raw, choisir JSON (application/json) et
saisir des données sous format JSON correspondant à l’objet personne à ajouter

ch r e
{
©A
"username": "wick",
"password": "wick"
}

Cliquer sur Send puis copier le jeton

H & H: Research and Training 46 / 47


Intégration de JWT

Spring Boot

Pour obtenir la liste des personnes avec Postman

Dans la liste déroulante, choisir GET puis saisir l’URL vers notre
web service [Link] H I ©
UEL
O
Dans le Headers, saisir Content-Type comme Key et
E
application/json comme Value
f LM
r e
et coller© Ach cliquer sur Type, choisir Bearer Token
Dans Authorization,
le token
Cliquer sur Send

H & H: Research and Training 47 / 47

Vous aimerez peut-être aussi