net.leanix.dropkit.oauth.OAuth2Authenticator Maven / Gradle / Ivy
package net.leanix.dropkit.oauth;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.dropwizard.auth.AuthenticationException;
import io.dropwizard.auth.Authenticator;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import net.leanix.dropkit.oauth.models.User;
import net.leanix.dropkit.oauth.token.OAuth2Token;
import net.leanix.dropkit.oauth.token.OAuth2TokenConfig;
import net.leanix.dropkit.oauth.token.OAuth2TokenParser;
/**
* Authenticator used to protect resources.
*
*
*/
@Singleton
public class OAuth2Authenticator implements Authenticator {
private final Logger logger = LoggerFactory.getLogger(OAuth2Authenticator.class);
private final OAuth2TokenParser parser;
private final Class userClass;
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.disableDefaultTyping();
}
@Inject
public OAuth2Authenticator(OAuth2TokenConfig config, Class userClass) {
try {
this.parser = new OAuth2TokenParser(config);
this.userClass = userClass;
} catch (Exception e) {
throw new RuntimeException("unhandleable exception", e);
}
}
/*
* (non-Javadoc)
*
* @see com.yammer.dropwizard.auth.Authenticator#authenticate(java.lang.Object)
*/
@Override
public Optional authenticate(String accessToken) throws AuthenticationException {
if (accessToken == null)
{
logger.warn("No token provided");
return Optional.empty();
}
try {
OAuth2Token token = this.parser.parse(accessToken, userClass);
return Optional.ofNullable(token.getPrincipal());
} catch (ExpiredJwtException ex) {
logger.warn("Token expired");
return Optional.empty();
} catch (JwtException ex) {
logger.warn("Unable to verify token");
return Optional.empty();
} catch (Throwable ex) {
throw new AuthenticationException("Unable to authenticate token", ex);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy