/** * Creates a {@link Credential} objects with the given {@link TokensAndUrlAuthData} which supports * refreshing tokens. */ public Credential createCredential(TokensAndUrlAuthData authData) { return new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()) .setTransport(httpTransport) .setJsonFactory(jsonFactory) .setClientAuthentication( new ClientParametersAuthentication(appCredentials.getKey(), appCredentials.getSecret())) .setTokenServerEncodedUrl(authData.getTokenServerEncodedUrl()) .build() .setAccessToken(authData.getAccessToken()) .setRefreshToken(authData.getRefreshToken()) .setExpiresInSeconds(EXPIRE_TIME_IN_SECONDS); } }
/** * @param credential credential whose {@link Credential#setAccessToken access token}, * {@link Credential#setRefreshToken refresh token}, and * {@link Credential#setExpirationTimeMilliseconds expiration time} need to be set if the * credential already exists in storage */ void load(Credential credential) { credential.setAccessToken(accessToken); credential.setRefreshToken(refreshToken); credential.setExpirationTimeMilliseconds(expirationTimeMillis); }
Credential credential = new GoogleCredential.Builder() .setClientSecrets("...") .... .build(); credential.setAccessToken(storedAccessToken); credential.setRefreshToken(storedRefreshToken)
/** * Load information into the credential. * * @param credential credential whose {@link Credential#setAccessToken access token}, * {@link Credential#setRefreshToken refresh token}, and * {@link Credential#setExpirationTimeMilliseconds expiration time} need to be set if the * credential already exists in storage */ void load(Credential credential) { credential.setAccessToken(accessToken); credential.setRefreshToken(refreshToken); credential.setExpirationTimeMilliseconds(expirationTimeMillis); } }
@Override public GoogleCredential setRefreshToken(String refreshToken) { if (refreshToken != null) { Preconditions.checkArgument( getJsonFactory() != null && getTransport() != null && getClientAuthentication() != null, "Please use the Builder and call setJsonFactory, setTransport and setClientSecrets"); } return (GoogleCredential) super.setRefreshToken(refreshToken); }
@Override public Sheets makeClient(String clientId, String clientSecret, String applicationName, String refreshToken, String accessToken) { if (clientId == null || clientSecret == null) { throw new IllegalArgumentException("clientId and clientSecret are required to create Google Sheets client."); } try { Credential credential = authorize(clientId, clientSecret); if (refreshToken != null && !"".equals(refreshToken)) { credential.setRefreshToken(refreshToken); } if (accessToken != null && !"".equals(accessToken)) { credential.setAccessToken(accessToken); } return new Sheets.Builder(transport, jsonFactory, credential) .setApplicationName(applicationName) .build(); } catch (Exception e) { throw new RuntimeCamelException("Could not create Google Sheets client.", e); } }
@Override public Calendar makeClient(String clientId, String clientSecret, Collection<String> scopes, String applicationName, String refreshToken, String accessToken, String emailAddress, String p12FileName, String user) { boolean serviceAccount = false; // if emailAddress and p12FileName values are present, assume Google Service Account if (null != emailAddress && !"".equals(emailAddress) && null != p12FileName && !"".equals(p12FileName)) { serviceAccount = true; } if (!serviceAccount && (clientId == null || clientSecret == null)) { throw new IllegalArgumentException("clientId and clientSecret are required to create Google Calendar client."); } try { Credential credential; if (serviceAccount) { credential = authorizeServiceAccount(emailAddress, p12FileName, scopes, user); } else { credential = authorize(clientId, clientSecret, scopes); if (refreshToken != null && !"".equals(refreshToken)) { credential.setRefreshToken(refreshToken); } if (accessToken != null && !"".equals(accessToken)) { credential.setAccessToken(accessToken); } } return new Calendar.Builder(transport, jsonFactory, credential).setApplicationName(applicationName).build(); } catch (Exception e) { throw new RuntimeCamelException("Could not create Google Calendar client.", e); } }
String CLIENT_ID = "see instructions in accepted answer"; String CLIENT_SECRET = "see instructions in accepted answer"; String REFRESH_TOKEN = "see instructions in accepted answer"; Builder builder = new GoogleCredential.Builder(); builder.setTransport(GoogleNetHttpTransport.newTrustedTransport()); builder.setJsonFactory(JacksonFactory.getDefaultInstance()); builder.setClientSecrets(CLIENT_ID, CLIENT_SECRET); Credential credential = builder.build(); credential.setRefreshToken(REFRESH_TOKEN); credential.refreshToken(); // gets the access token, using the refresh token ContactsService contactsService.setOAuth2Credentials(credential); Query query = new Query(new URL("https://www.google.com/m8/feeds/contacts/default/full")); query.setMaxResults(10_000); ContactFeed allContactsFeed = contactsService.getFeed(query, ContactFeed.class); LOGGER.log(Level.INFO, allContactsFeed.getTitle().getPlainText()); for(ContactEntry contact : allContactsFeed.getEntries()) { ... }
@Test public void testRefreshCredential_refreshFailedNoException() throws Exception { credential.setAccessToken(ACCESS_TOKEN); credential.setRefreshToken(REFRESH_TOKEN); credential.setExpiresInSeconds(REFRESH_WINDOW_SECS - 10L); Mockito.doReturn(false).when(oAuth2Helper).callRefreshToken(credential); oAuth2Helper.refreshCredential(credential); }
@Test public void testRefreshCredential_refreshFailedException() throws Exception { credential.setAccessToken(ACCESS_TOKEN); credential.setRefreshToken(REFRESH_TOKEN); credential.setExpiresInSeconds(REFRESH_WINDOW_SECS - 10L); Mockito.doThrow(new IOException("Failed")).when(oAuth2Helper).callRefreshToken(credential); thrown.expect(IOException.class); oAuth2Helper.refreshCredential(credential); } }
@Test public void testRefreshCredential_refresh() throws Exception { credential.setAccessToken(ACCESS_TOKEN); credential.setRefreshToken(REFRESH_TOKEN); credential.setExpiresInSeconds(REFRESH_WINDOW_SECS - 10L); Mockito.doReturn(true).when(oAuth2Helper).callRefreshToken(credential); oAuth2Helper.refreshCredential(credential); verify(oAuth2Helper).callRefreshToken(credential); }
@Override public boolean load(String userId, Credential credential) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(KIND, userId); try { Entity entity = datastore.get(key); credential.setAccessToken((String) entity.getProperty("accessToken")); credential.setRefreshToken((String) entity.getProperty("refreshToken")); credential.setExpirationTimeMilliseconds((Long) entity.getProperty("expirationTimeMillis")); return true; } catch (EntityNotFoundException exception) { return false; } }
public boolean load(String userId, Credential credential) throws IOException { Session session = persistence.getSession(table.getDatabaseName()); Column idColumn = DatabaseLogic.findColumnByPropertyName(table, idProperty); Object idValue = OgnlUtils.convertValue(userId, idColumn.getActualJavaType()); Criteria criteria = session.createCriteria(table.getActualEntityName()).add(Restrictions.eq(idProperty, idValue)); TableAccessor tableAccessor = new TableAccessor(table); Object record = criteria.uniqueResult(); if(record == null) { return false; } try { Object value = tableAccessor.getProperty(accessTokenProperty).get(record); credential.setAccessToken((String) value); value = tableAccessor.getProperty(refreshTokenProperty).get(record); credential.setRefreshToken((String) value); value = tableAccessor.getProperty(expirationProperty).get(record); credential.setExpirationTimeMilliseconds((Long) OgnlUtils.convertValue(value, Long.class)); return true; } catch (NoSuchFieldException e) { throw new Error(e); } }
public boolean load(String userId, Credential credential) throws IOException { Session session = persistence.getSession(table.getDatabaseName()); Column idColumn = DatabaseLogic.findColumnByPropertyName(table, idProperty); Object idValue = OgnlUtils.convertValue(userId, idColumn.getActualJavaType()); Criteria criteria = session.createCriteria(table.getActualEntityName()).add(Restrictions.eq(idProperty, idValue)); TableAccessor tableAccessor = new TableAccessor(table); Object record = criteria.uniqueResult(); if(record == null) { return false; } try { Object value = tableAccessor.getProperty(accessTokenProperty).get(record); credential.setAccessToken((String) value); value = tableAccessor.getProperty(refreshTokenProperty).get(record); credential.setRefreshToken((String) value); value = tableAccessor.getProperty(expirationProperty).get(record); credential.setExpirationTimeMilliseconds((Long) OgnlUtils.convertValue(value, Long.class)); return true; } catch (NoSuchFieldException e) { throw new Error(e); } }
@Test public void testRefreshCredential_notSoonEnough() throws Exception { credential.setAccessToken(ACCESS_TOKEN); credential.setRefreshToken(REFRESH_TOKEN); credential.setExpiresInSeconds(REFRESH_WINDOW_SECS * 2L); assertSame(credential, oAuth2Helper.refreshCredential(credential)); }
@Test public void testRefreshCredential_noRefreshToken() throws Exception { credential.setAccessToken(ACCESS_TOKEN); credential.setRefreshToken(null); credential.setExpiresInSeconds(null); assertSame(credential, oAuth2Helper.refreshCredential(credential)); }
credential.setRefreshToken("refreshToken2"); credential.setExpiresInSeconds(1000L);