Last active
October 12, 2015 12:43
-
-
Save huljas/6aa4e26e8c9128fffba5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.jose4j.jwk.HttpsJwks; | |
import org.jose4j.jwt.consumer.InvalidJwtException; | |
import org.jose4j.jwt.consumer.JwtConsumer; | |
import org.jose4j.jwt.consumer.JwtConsumerBuilder; | |
import org.jose4j.jwt.consumer.JwtContext; | |
import org.jose4j.keys.resolvers.HttpsJwksVerificationKeyResolver; | |
/** | |
* Simple authentication that can be used to validate google oauth tokens. | |
* <p> | |
* Uses the certificates from https://www.googleapis.com/oauth2/v2/certs | |
* </p> | |
* @author Heikki Uljas | |
*/ | |
public class GoogleAuthenticator { | |
private final String clientId; | |
private final HttpsJwksVerificationKeyResolver httpsJwksKeyResolver; | |
/** | |
* Create new authenticator instance which can be used for google jwt token validation. | |
* | |
* @param clientId The OAuth 2.0 client IDs from console.google.com - Credentials. | |
*/ | |
public GoogleAuthenticator(String clientId) { | |
this.clientId = clientId; | |
HttpsJwks httpsJkws = new HttpsJwks("https://www.googleapis.com/oauth2/v2/certs"); | |
httpsJwksKeyResolver = new HttpsJwksVerificationKeyResolver(httpsJkws); | |
} | |
/** | |
* Validates given access token and returns the user email. | |
* | |
* @return Email from a valid token or null if the token is invalid. | |
*/ | |
public String validate(String jwt, int allowedSkewSeconds) { | |
try { | |
JwtConsumer jwtConsumer = new JwtConsumerBuilder() | |
.setRequireExpirationTime() // the JWT must have an expiration time | |
.setAllowedClockSkewInSeconds(allowedSkewSeconds) // allow some leeway in validating time based claims to account for clock skew | |
.setRequireSubject() // the JWT must have a subject claim | |
.setExpectedIssuer("accounts.google.com") // whom the JWT needs to have been issued by | |
.setExpectedAudience(clientId) // to whom the JWT is intended for | |
.setVerificationKeyResolver(httpsJwksKeyResolver) | |
.build(); | |
JwtContext jwtContext = jwtConsumer.process(jwt); | |
String email = (String) jwtContext.getJwtClaims().getClaimValue("email"); | |
return email; | |
} catch (InvalidJwtException e) { | |
// LOG | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment