Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleCredential setExpirationTimeMilliseconds

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential setExpirationTimeMilliseconds

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.auth.oauth2 GoogleCredential setExpirationTimeMilliseconds.

Prototype

@Override
    public GoogleCredential setExpirationTimeMilliseconds(Long expirationTimeMilliseconds) 

Source Link

Usage

From source file:com.alow.servlet.ConnectServlet.java

License:Open Source License

/**
 * Verify that the token in the given credential is valid.
 * @param credential Credential to verify.
 * @return Google user ID for which token was issued.
 * @throws TokenVerificationException Credential is not valid.
 * @throws IOException Could not verify Credential because of a network
 *                     failure.// w  w  w.j  a  va  2 s .  com
 */
private String verifyToken(GoogleCredential credential) throws TokenVerificationException, IOException {
    // Check that the token is valid.
    Oauth2 oauth2 = new Oauth2.Builder(TRANSPORT, JSON_FACTORY, credential).build();
    Tokeninfo tokenInfo = oauth2.tokeninfo().setAccessToken(credential.getAccessToken()).execute();
    // If there was an error in the token info, abort.
    if (tokenInfo.containsKey("error")) {
        throw new TokenVerificationException(tokenInfo.get("error").toString());
    }

    if (credential.getExpiresInSeconds() == null) {
        // Set the expiry time if it hasn't already been set.
        int expiresIn = tokenInfo.getExpiresIn();
        credential.setExpiresInSeconds((long) expiresIn);
        credential.setExpirationTimeMilliseconds(System.currentTimeMillis() + expiresIn * 1000);
    }

    Pattern p = Pattern.compile("(\\d+)([-]?)(.*)$");
    Matcher issuedTo = p.matcher(CLIENT_ID);
    Matcher localId = p.matcher(tokenInfo.getIssuedTo());

    // Make sure the token we got is for our app.
    if (!issuedTo.matches() || !localId.matches() || !issuedTo.group(1).equals(localId.group(1))) {

        throw new TokenVerificationException("Token's client ID does not match app's.");
    }

    return tokenInfo.getUserId();
}