Refactoring - Bonne version améliorée
This commit is contained in:
60
src/main/java/com/lions/dev/service/JwtService.java
Normal file
60
src/main/java/com/lions/dev/service/JwtService.java
Normal file
@@ -0,0 +1,60 @@
|
||||
package com.lions.dev.service;
|
||||
|
||||
import com.lions.dev.entity.users.Users;
|
||||
import io.smallrye.jwt.build.Jwt;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Service d'émission de JWT au login.
|
||||
* Le token contient sub (userId), groups (rôle) et est signé avec la clé secrète configurée.
|
||||
* La validation des tokens sur les requêtes est assurée par quarkus-smallrye-jwt
|
||||
* lorsque les endpoints sont protégés avec @RolesAllowed.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class JwtService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(JwtService.class);
|
||||
private static final String ISSUER = "afterwork";
|
||||
|
||||
@ConfigProperty(name = "afterwork.jwt.secret", defaultValue = "afterwork-jwt-secret-min-32-bytes-for-hs256!")
|
||||
String secret;
|
||||
|
||||
/**
|
||||
* Génère un JWT pour l'utilisateur authentifié.
|
||||
*
|
||||
* @param user L'utilisateur après login réussi
|
||||
* @return Le token JWT signé (à envoyer au client dans la réponse d'authentification)
|
||||
*/
|
||||
public String generateToken(Users user) {
|
||||
if (user == null || user.getId() == null) {
|
||||
throw new IllegalArgumentException("User et id obligatoires pour générer le JWT");
|
||||
}
|
||||
Set<String> groups = Set.of("user", user.getRole() != null ? user.getRole() : "USER");
|
||||
SecretKey key = secretKeyFromConfig();
|
||||
String token = Jwt.claims()
|
||||
.issuer(ISSUER)
|
||||
.subject(user.getId().toString())
|
||||
.groups(groups)
|
||||
.jws()
|
||||
.sign(key);
|
||||
LOG.debug("JWT généré pour l'utilisateur " + user.getId());
|
||||
return token;
|
||||
}
|
||||
|
||||
private SecretKey secretKeyFromConfig() {
|
||||
byte[] decoded = secret.getBytes(StandardCharsets.UTF_8);
|
||||
if (decoded.length < 32) {
|
||||
byte[] padded = new byte[32];
|
||||
System.arraycopy(decoded, 0, padded, 0, decoded.length);
|
||||
decoded = padded;
|
||||
}
|
||||
return new SecretKeySpec(decoded, "HmacSHA256");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user