private boolean needsRefresh(final AccessToken accessToken) { if (accessToken == null) { // has not yet been fetched return true; } final Date expirationTime = credentials.getAccessToken().getExpirationTime(); // Don't refresh if expiration time hasn't been provided. if (expirationTime == null) { return false; } // refresh the token if it expires "soon" final long expiresIn = expirationTime.getTime() - clock.millis(); return expiresIn <= minimumExpiryMillis; }
@Test public void constructor() { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); assertEquals(TOKEN, accessToken.getTokenValue()); assertEquals(EXPIRATION_DATE, accessToken.getExpirationTime()); assertEquals(EXPIRATION_DATE.getTime(), (long) accessToken.getExpirationTimeMillis()); }
private long getRefreshDelay(AccessToken accessToken) { return accessToken.getExpirationTime().getTime() - System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5); }
private HeaderCacheElement(AccessToken token) { if (token.getExpirationTime() == null) { actualExpirationTimeMs = Long.MAX_VALUE; } else { actualExpirationTimeMs = token.getExpirationTime().getTime(); } this.token = new HeaderToken(Status.OK, "Bearer " + token.getTokenValue()); }
/** * Return the remaining time the current access token will be valid, or null if there is no * token or expiry information. Must be called under lock. */ private Long getExpiresInMilliseconds() { if (temporaryAccess == null) { return null; } Date expirationTime = temporaryAccess.getExpirationTime(); if (expirationTime == null) { return null; } return (expirationTime.getTime() - clock.currentTimeMillis()); }
/** * Return the remaining time the current access token will be valid, or null if there is no * token or expiry information. Must be called under lock. */ private Long getExpiresInMilliseconds() { if (temporaryAccess == null) { return null; } Date expirationTime = temporaryAccess.getExpirationTime(); if (expirationTime == null) { return null; } return (expirationTime.getTime() - clock.currentTimeMillis()); }
@Override public final synchronized void onChanged(OAuth2Credentials credentials) { if (state.get() != State.STARTED) { return; } AccessToken accessToken = credentials.getAccessToken(); long refreshDelay = getRefreshDelay(accessToken); if (refreshDelay > 0) { scheduleRefresh(refreshDelay); } else { logger.warn("Token expiry ({}) is less than 5 minutes in the future. Not " + "scheduling a proactive refresh.", accessToken.getExpirationTime()); } }
@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; }
@Override protected void onPostExecute(AccessToken accessToken) { mAccessTokenTask = null; final ManagedChannel channel = new OkHttpChannelProvider() .builderForAddress(HOSTNAME, PORT) .nameResolverFactory(new DnsNameResolverProvider()) .intercept(new GoogleCredentialsInterceptor(new GoogleCredentials(accessToken) .createScoped(SCOPE))) .build(); mApi = SpeechGrpc.newStub(channel); // Schedule access token refresh before it expires if (mHandler != null) { mHandler.postDelayed(mFetchAccessTokenRunnable, Math.max(accessToken.getExpirationTime().getTime() - System.currentTimeMillis() - ACCESS_TOKEN_FETCH_MARGIN, ACCESS_TOKEN_EXPIRATION_TOLERANCE)); } } }
/** * Puts the end user credentials in long term storage. * * @param userId Application's identifier for the end user. * @param credentials UserCredentials instance for the authorized consent. * @throws IOException An error storing the credentials. */ public void storeCredentials(String userId, UserCredentials credentials) throws IOException { if (tokenStore == null) { throw new IllegalStateException("Cannot store tokens if tokenStore is not specified."); } AccessToken accessToken = credentials.getAccessToken(); String acessTokenValue = null; Date expiresBy = null; if (accessToken != null) { acessTokenValue = accessToken.getTokenValue(); expiresBy = accessToken.getExpirationTime(); } String refreshToken = credentials.getRefreshToken(); GenericJson tokenStateJson = new GenericJson(); tokenStateJson.setFactory(OAuth2Utils.JSON_FACTORY); tokenStateJson.put("access_token", acessTokenValue); tokenStateJson.put("expiration_time_millis", expiresBy.getTime()); if (refreshToken != null) { tokenStateJson.put("refresh_token", refreshToken); } String tokenState = tokenStateJson.toString(); tokenStore.store(userId, tokenState); }
/** * Puts the end user credentials in long term storage. * * @param userId Application's identifier for the end user. * @param credentials UserCredentials instance for the authorized consent. * @throws IOException An error storing the credentials. */ public void storeCredentials(String userId, UserCredentials credentials) throws IOException { if (tokenStore == null) { throw new IllegalStateException("Cannot store tokens if tokenStore is not specified."); } AccessToken accessToken = credentials.getAccessToken(); String acessTokenValue = null; Date expiresBy = null; if (accessToken != null) { acessTokenValue = accessToken.getTokenValue(); expiresBy = accessToken.getExpirationTime(); } String refreshToken = credentials.getRefreshToken(); GenericJson tokenStateJson = new GenericJson(); tokenStateJson.setFactory(OAuth2Utils.JSON_FACTORY); tokenStateJson.put("access_token", acessTokenValue); tokenStateJson.put("expiration_time_millis", expiresBy.getTime()); if (refreshToken != null) { tokenStateJson.put("refresh_token", refreshToken); } String tokenState = tokenStateJson.toString(); tokenStore.store(userId, tokenState); }
@Test public void refreshAccessToken_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); AccessToken accessToken = credentials.refreshAccessToken(); assertEquals(EXPECTED_ACCESS_TOKEN, accessToken.getTokenValue()); assertEquals(EXPECTED_EXPIRATION_DATE, accessToken.getExpirationTime()); }
@Test public void refreshAccessToken_sameAs() throws IOException { final String expectedAccessToken = "ExpectedAccessToken"; MockAppIdentityService appIdentity = new MockAppIdentityService(); appIdentity.setAccessTokenText(expectedAccessToken); appIdentity.setExpiration(new Date(System.currentTimeMillis() + 60L * 60L * 100L)); AppEngineCredentials credentials = AppEngineCredentials.newBuilder() .setScopes(SCOPES) .setAppIdentityService(appIdentity) .build(); AccessToken accessToken = credentials.refreshAccessToken(); assertEquals(appIdentity.getAccessTokenText(), accessToken.getTokenValue()); assertEquals(appIdentity.getExpiration(), accessToken.getExpirationTime()); }
@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()); }