io.dropwizard.auth.CachingAuthenticator Maven / Gradle / Ivy
package io.dropwizard.auth;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.codahale.metrics.caffeine.MetricsStatsCounter;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.CaffeineSpec;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import com.github.benmanes.caffeine.cache.stats.StatsCounter;
import java.security.Principal;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletionException;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static com.codahale.metrics.MetricRegistry.name;
/**
* An {@link Authenticator} decorator which uses a Caffeine cache to temporarily
* cache credentials and their corresponding principals.
*
* @param the type of credentials the authenticator can authenticate
* @param the type of principals the authenticator returns
*/
public class CachingAuthenticator implements Authenticator {
private final LoadingCache> cache;
private final Meter cacheMisses;
private final Timer gets;
/**
* Creates a new cached authenticator.
*
* @param metricRegistry the application's registry of metrics
* @param authenticator the underlying authenticator
* @param cacheSpec a {@link CaffeineSpec}
*/
public CachingAuthenticator(final MetricRegistry metricRegistry,
final Authenticator authenticator,
final CaffeineSpec cacheSpec) {
this(metricRegistry, authenticator, Caffeine.from(cacheSpec), false);
}
/**
* Creates a new cached authenticator.
*
* @param metricRegistry the application's registry of metrics
* @param authenticator the underlying authenticator
* @param builder a {@link Caffeine}
*/
public CachingAuthenticator(final MetricRegistry metricRegistry,
final Authenticator authenticator,
final Caffeine