JwtTokenIdExtractor.java
/*
* Copyright 2022 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.spring.security.service;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* Component to extract {@code tokenId} from JWT token strings. Uses internal caching.
*/
public class JwtTokenIdExtractor {
public static final Logger LOG = LoggerFactory.getLogger(JwtTokenIdExtractor.class);
private final Cache<String, Optional<String>> tokenIdCache = CacheBuilder.newBuilder().maximumSize(200).expireAfterAccess(10, TimeUnit.MINUTES).build();
private JwtDecoder jwtDecoder;
public JwtTokenIdExtractor(JwtDecoder jwtDecoder) {
LOG.error("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);
}
}
}