Add Logger

This commit is contained in:
harish
2024-08-21 19:54:27 +05:30
parent 7a080504aa
commit 04e9ff57a7
5 changed files with 164 additions and 76 deletions

View File

@@ -36,26 +36,35 @@ public class TokenProvider {
@PostConstruct
public void init() {
this.key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
log.info("JWT Secret Key initialized.");
}
public String createToken(Authentication authentication,Boolean rememberMe) {
public String createToken(Authentication authentication, Boolean rememberMe) {
String authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));
Long now = null;
Date validity=null;
if(Boolean.TRUE.equals(rememberMe)) {
now= DateUtils.addMonths(new Date(), 2).getTime();
Long now;
Date validity;
if (Boolean.TRUE.equals(rememberMe)) {
now = DateUtils.addMonths(new Date(), 2).getTime();
validity = new Date(now);
}else {
now=(new Date()).getTime();
log.info("Creating token with extended validity for 2 months.");
} else {
now = (new Date()).getTime();
validity = new Date(now + (this.tokenValidityInSeconds * 1000));
log.info("Creating token with standard validity of {} seconds.", this.tokenValidityInSeconds);
}
return Jwts.builder()
String token = Jwts.builder()
.setSubject(authentication.getName())
.claim("auth", authorities)
.signWith(key, SignatureAlgorithm.HS512)
.setExpiration(validity)
.compact();
log.debug("Generated token: {}", token);
return token;
}
public Authentication getAuthentication(String token) {
@@ -64,18 +73,21 @@ public class TokenProvider {
.build()
.parseClaimsJws(token)
.getBody();
UserDetails principal = new User(claims.getSubject(), "", Collections.emptyList());
return new UsernamePasswordAuthenticationToken(principal, token, principal.getAuthorities());
UserDetails principal = new User(claims.getSubject(), "", Collections.emptyList());
log.info("Authenticated user: {}", claims.getSubject());
return new UsernamePasswordAuthenticationToken(principal, token, ClaimsToAuthorities(claims.get("auth")));
}
private Collection<? extends GrantedAuthority> ClaimsToAuthorities(Object authClaim) {
return authClaim == null || ((String) authClaim).isEmpty() ?
Collection<? extends GrantedAuthority> authorities = authClaim == null || ((String) authClaim).isEmpty() ?
Collections.emptyList() :
Arrays.stream(((String) authClaim).split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
log.debug("Converted authorities from claims: {}", authorities);
return authorities;
}
public boolean validateToken(String authToken) {
@@ -84,9 +96,10 @@ public class TokenProvider {
.setSigningKey(key)
.build()
.parseClaimsJws(authToken);
log.info("Token is valid.");
return true;
} catch (Exception e) {
log.info("Token validation failed: " + e.getMessage());
log.error("Token validation failed: {}", e.getMessage());
return false;
}
}