/** * 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); } }
@Override public GoogleCredential setAccessToken(String accessToken) { return (GoogleCredential) super.setAccessToken(accessToken); }
/** * @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); }
private Credential creds; /** * Keep the expiration time of the access token to renew it before expiry */ private Calendar expirationTime = Calendar.getInstance(); protected void initCredentials() { List<String> scopes = Arrays.asList("https://spreadsheets.google.com/feeds"); AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes); expirationTime.setTime(accessToken.getExpirationTime()); expirationTime.add(Calendar.MINUTE,-REFRESH_MINUTES); //refresh some time before expiry creds = new Credential(BearerToken.authorizationHeaderAccessMethod()); creds.setAccessToken(accessToken.getAccessToken()); } public SpreadsheetUtil(String appname) { myService = new SpreadsheetService(appname); myService.setOAuth2Credentials(cred); }
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 protected HttpRequestFactory getRequestFactory() throws APIException { String accessToken = getAccessToken(); final Credential credential = new Credential.Builder(BearerToken.queryParameterAccessMethod()).build(); if (StringUtils.isNotBlank(accessToken)) { credential.setAccessToken(accessToken); } return httpTransport.createRequestFactory(credential); }
@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); } }
cred.setAccessToken(accessToken); servletRequest.setAttribute(ATTRIBUTE_KEY, cred);
@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)); }
.build(); credential.setAccessToken("accessToken2"); credential.setRefreshToken("refreshToken2"); credential.setExpiresInSeconds(1000L);