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.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.apache.commons.lang3.StringUtils;
import org.springframework.security.oauth2.jwt.JwtDecoder;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

/**
 * 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.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);
		}
	}

}