private static GoogleCredentials getComputeEngineCredentials() throws IOException { try { GoogleCredentials credentials = ComputeEngineCredentials.create(); credentials.refreshAccessToken(); return credentials; } catch (IOException e) { throw new IOException("Unable to get credentials from the environment. " + "Please explicitly set the account key.", e); } }
@Override protected AccessToken doInBackground(Void... voids) { final SharedPreferences prefs = mContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE); String tokenValue = prefs.getString(PREF_ACCESS_TOKEN_VALUE, null); long expirationTime = prefs.getLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME, -1); // Check if the current token is still valid for a while if (tokenValue != null && expirationTime > 0) { if (expirationTime > System.currentTimeMillis() + ACCESS_TOKEN_EXPIRATION_TOLERANCE) { return new AccessToken(tokenValue, new Date(expirationTime)); } } final InputStream stream = mContext.getResources().openRawResource(R.raw.credential); try { final GoogleCredentials credentials = GoogleCredentials.fromStream(stream).createScoped(SCOPE); final AccessToken token = credentials.refreshAccessToken(); prefs.edit() .putString(PREF_ACCESS_TOKEN_VALUE, token.getTokenValue()) .putLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME, token.getExpirationTime().getTime()) .apply(); return token; } catch (IOException e) { Log.e(TAG, "Failed to obtain access token.", e); } return null; }
.setAuthPort(authSocket.getLocalPort()) .build(); assertEquals("token", creds.refreshAccessToken().getTokenValue()); } finally { authSocket.close();
@Test public void createScoped_clonesWithScopes() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(null); assertTrue(credentials.createScopedRequired()); try { credentials.refreshAccessToken(); fail("Should not be able to use credential without scopes."); } catch (Exception expected) { // Expected } GoogleCredentials scopedCredentials = credentials.createScoped(SCOPES); assertNotSame(credentials, scopedCredentials); AccessToken accessToken = scopedCredentials.refreshAccessToken(); assertEquals(EXPECTED_ACCESS_TOKEN, accessToken.getTokenValue()); assertEquals(EXPECTED_EXPIRATION_DATE, accessToken.getExpirationTime()); }