private String generateParamsString(Optional<Map<String, String>> params) { Map<String, String> updatedParams = new ArrayMap<>(); if (params.isPresent()) { updatedParams.putAll(params.get()); } if (!updatedParams.containsKey(ACCESS_TOKEN_KEY)) { updatedParams.put(ACCESS_TOKEN_KEY, credential.getAccessToken()); } List<String> orderedKeys = updatedParams.keySet().stream().collect(Collectors.toList()); Collections.sort(orderedKeys); List<String> paramStrings = new ArrayList<>(); for (String key : orderedKeys) { String k = key.trim(); String v = updatedParams.get(key).trim(); paramStrings.add(k + "=" + v); } return String.join("&", paramStrings); }
/** * 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); } }
public GoogleWebmasterClientImpl(Credential credential, String appName) throws IOException { //transport: new NetHttpTransport() or GoogleNetHttpTransport.newTrustedTransport() //jsonFactory: new JacksonFactory() or JacksonFactory.getDefaultInstance() _service = new Webmasters.Builder(credential.getTransport(), GoogleCommon.getJsonFactory(), credential) .setApplicationName(appName).build(); _analytics = _service.searchanalytics(); }
/** * Store information from the credential. * * @param credential credential whose {@link Credential#getAccessToken access token}, * {@link Credential#getRefreshToken refresh token}, and * {@link Credential#getExpirationTimeMilliseconds expiration time} need to be stored */ void store(Credential credential) { accessToken = credential.getAccessToken(); refreshToken = credential.getRefreshToken(); expirationTimeMillis = credential.getExpirationTimeMilliseconds(); }
/** * Refresh the Google Cloud API access token, if necessary. */ private void refreshAccessToken() { final Long expiresIn = credential.getExpiresInSeconds(); // trigger refresh if token is about to expire String accessToken = credential.getAccessToken(); if (accessToken == null || expiresIn != null && expiresIn <= 60) { try { credential.refreshToken(); accessToken = credential.getAccessToken(); } catch (final IOException e) { log.error("Failed to fetch access token", e); } } if (accessToken != null) { this.accessToken = accessToken; } }
public OneDriveCredential(Credential credential, String businessResource) { super(new Credential.Builder(credential.getMethod()).setTransport(credential.getTransport()) .setJsonFactory(credential.getJsonFactory()) .setTokenServerEncodedUrl( credential.getTokenServerEncodedUrl()) .setClientAuthentication( credential.getClientAuthentication()) .setRequestInitializer(credential.getRequestInitializer()) .setRefreshListeners(credential.getRefreshListeners()) .setClock(credential.getClock())); setAccessToken(credential.getAccessToken()); setRefreshToken(credential.getRefreshToken()); setExpirationTimeMilliseconds(credential.getExpirationTimeMilliseconds()); this.businessResource = Objects.requireNonNull(businessResource); }
@Test public void loadCredential() throws Exception { OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("http://redirect") .setHttpTransport(mockHttpTransport) .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST)) .build(); oAuth2Credentials.authenticate("authorizationCode", "userId"); Credential credential = oAuth2Credentials.loadCredential("userId"); assertEquals("Refresh token does not match.", "refreshToken", credential.getRefreshToken()); assertTrue("Expected expires_in between 0 and 3600. Was actually: " + credential.getExpiresInSeconds(), credential.getExpiresInSeconds() > 0 && credential.getExpiresInSeconds() <= 3600); assertEquals("Access token does not match.", "accessToken", credential.getAccessToken()); assertEquals("Access method (Bearer) does not match", BearerToken.authorizationHeaderAccessMethod().getClass(), credential.getMethod().getClass()); }
.build(); credential.setAccessToken("accessToken2"); credential.setRefreshToken("refreshToken2"); credential.setExpiresInSeconds(1000L); Credential loadedCredential = oAuth2Credentials.loadCredential("userId"); assertEquals("Refresh token does not match.", "refreshToken", storedCredential.getRefreshToken()); assertTrue("Expected expires_in between 0 and 3600. Was actually: " + storedCredential.getExpiresInSeconds(), storedCredential.getExpiresInSeconds() > 0 && storedCredential.getExpiresInSeconds() <= 3600); assertEquals("Access token does not match.", "accessToken", storedCredential.getAccessToken()); assertEquals("Access method (Bearer) does not match", BearerToken.authorizationHeaderAccessMethod().getClass(), storedCredential.getMethod().getClass()); assertEquals("Refresh token does not match.", "refreshToken2", loadedCredential.getRefreshToken()); assertTrue("Expected expires_in between 0 and 1000. Was actually: " + loadedCredential.getExpiresInSeconds(), loadedCredential.getExpiresInSeconds() > 0 && loadedCredential.getExpiresInSeconds() <= 1000L); assertEquals("Access token does not match.", "accessToken2", loadedCredential.getAccessToken()); assertEquals("Access method (Bearer) does not match", BearerToken.authorizationHeaderAccessMethod().getClass(), loadedCredential.getMethod().getClass());
credential = getCredential(); String accessToken = credential.getAccessToken(); Long expiresIn = credential.getExpiresInSeconds(); if ( credential.refreshToken() ) accessToken = credential.getAccessToken(); Long expirationTimeMilliseconds = credential.getExpirationTimeMilliseconds(); if ( expirationTimeMilliseconds != null )
public void store(Credential credential) { this.credential = Optional.of(credential); Properties properties = new Properties(); properties.setProperty(PROP_ACCESS_TOKEN, credential.getAccessToken()); properties.setProperty(PROP_REFRESH_TOKEN, credential.getRefreshToken()); try { File file = getAuthenticationFile(options); properties.store(new FileWriter(file), "Properties of jdrivesync."); } catch (IOException e) { throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to store properties file: " + e.getMessage(), e); } }
/** * @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); }
/** * Returns {@code true} if the credential can and should be refreshed. */ @VisibleForTesting boolean isCredentialRefreshable(Credential credential) { return credential.getAccessToken() == null || credential.getExpiresInSeconds() != null && credential.getExpiresInSeconds() <= refreshWindowSeconds; } }
Credential credential = new GoogleCredential.Builder() .setClientSecrets("...") .... .build(); credential.setAccessToken(storedAccessToken); credential.setRefreshToken(storedRefreshToken)
/** * Tests generating OAuth2 credentials. */ @Test public void testGenerateCredential_defaultTransport() throws Exception { OfflineCredentials offlineCredentials = new OfflineCredentials.Builder(oAuth2Helper) .forApi(OfflineCredentials.Api.AD_MANAGER) .withClientSecrets("clientId", "clientSecret") .withRefreshToken("refreshToken") .build(); when(oAuth2Helper.callRefreshToken(Mockito.<Credential>anyObject())).thenReturn(true); Credential credential = offlineCredentials.generateCredential(); assertEquals( "clientId", ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientId()); assertEquals( "clientSecret", ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientSecret()); assertEquals("refreshToken", credential.getRefreshToken()); assertSame(ForApiBuilder.DEFAULT_HTTP_TRANSPORT, credential.getTransport()); }
Credential credential = newFlow().loadCredential(userId); if (credential.getRefreshToken() != null) { logger.log(Level.SEVERE, "Refresh token is not null"); } else { logger.log(Level.SEVERE, "Refresh token is null!"); }
// Fetch credential using the GoogleAuthorizationCodeFlow GoogleAuthorizationCodeFlow authorizationCodeFlow; Credential credential = authorizationCodeFlow.loadCredential(userId); if (credential != null) { try { // refresh the credential to see if the refresh token is still valid credential.refreshToken(); System.out.println("Refreshed: expires in: " + credential.getExpiresInSeconds()); } catch (TokenResponseException e) { // process exception here. // This will catch the Exception. // This Exception contains the HTTP status and reason etc. // In case of a revoke, this will throw something like a 401 - "invalid_grant" return; } } else { // No credential yet known. // Flow for creating a new credential here }
/** * Authorizes the installed application to access user's protected data. * * @param userId user ID or {@code null} if not using a persisted credential store * @return credential */ public Credential authorize(String userId) throws IOException { try { Credential credential = flow.loadCredential(userId); if (credential != null && (credential.getRefreshToken() != null || credential.getExpiresInSeconds() == null || credential.getExpiresInSeconds() > 60)) { return credential; } // open in browser String redirectUri = receiver.getRedirectUri(); AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUri); onAuthorization(authorizationUrl); // receive authorization code and exchange it for an access token String code = receiver.waitForCode(); TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute(); // store credential and return it return flow.createAndStoreCredential(response, userId); } finally { receiver.stop(); } }
@Override public GoogleCredential setAccessToken(String accessToken) { return (GoogleCredential) super.setAccessToken(accessToken); }
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()) { ... }
/** * Creates offline-friendly auth object using a credential object. * * Use this method when your application has already performed the oauth * flow and needs to store and use the credential later in an offline * manner (e.g., via Google Cloud Dataflow). * * @param credential The credential to be used for requests. */ public OfflineAuth(Credential credential) { Preconditions.checkNotNull(credential); ClientParametersAuthentication clientParams = (ClientParametersAuthentication) credential.getClientAuthentication(); this.clientId = clientParams.getClientId(); this.clientSecret = clientParams.getClientSecret(); this.refreshToken = credential.getRefreshToken(); }