JwtTokenIdExtractor.java
/*
* Copyright 2026 Global Crop Diversity Trust
* Licensed under the Apache License, Version 2.0
* See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
*/
package org.gringlobal.custom.security.service;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.StringUtils;
/**
* Component to extract {@code tokenId} from JWT token strings. Uses internal caching.
*/
@Slf4j
public class JwtTokenIdExtractor {
private final Cache<String, Optional<String>> tokenIdCache = CacheBuilder.newBuilder().maximumSize(200).expireAfterAccess(10, TimeUnit.MINUTES).build();
private JwtDecoder jwtDecoder;
public JwtTokenIdExtractor(JwtDecoder jwtDecoder) {
log.debug("Making JwtTokenIdExtractor instance");
this.jwtDecoder = jwtDecoder;
}
public String getJwtTokenId(String token) {
if (StringUtils.isBlank(token)) return null;
try {
return tokenIdCache.get(token, () -> {
try {
var jwt = jwtDecoder.decode(token);
return Optional.of(jwt.getId());
} catch (Exception e) {
return Optional.empty();
}
}).orElse(null);
} catch (ExecutionException e) {
log.error("Could not deal with: {}", e.getMessage(), e);
throw new RuntimeException(e);
}
}
}