final String token = accessTokenOpt.get().getTokenValue(); headers.put("Authorization", singletonList("Bearer " + token)); log.debug("Add Authorization header with bearer token");
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; }
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()); }
OAuth2AuthCredentials(String accessToken, Date expirationTime) { this.accessToken = checkNotNull(accessToken); this.expirationTime = expirationTime; this.credentials = new GoogleCredentials(new AccessToken(accessToken, expirationTime)); }
@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; }
@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()); }
@Test public void toString_containsFields() throws IOException { AccessToken accessToken = new AccessToken("1/MkSJoj1xsli0AccessToken_NKPY2", null); OAuth2Credentials credentials = OAuth2Credentials.newBuilder() .setAccessToken(accessToken) .build(); String expectedToString = String.format("OAuth2Credentials{requestMetadata=%s, temporaryAccess=%s}", ImmutableMap.of(AuthHttpConstants.AUTHORIZATION, ImmutableList.of(OAuth2Utils.BEARER_PREFIX + accessToken.getTokenValue())), accessToken.toString()); assertEquals(expectedToString, credentials.toString()); }
@Test public void constructor_storesAccessToken() { OAuth2Credentials credentials = OAuth2Credentials.newBuilder() .setAccessToken(new AccessToken(ACCESS_TOKEN, null)) .build(); assertEquals(credentials.getAccessToken().getTokenValue(), ACCESS_TOKEN); }
@Test public void refreshAccessToken_tokenExpiry() throws IOException { final String tokenString = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; ServiceAccountCredentials credentials = ServiceAccountCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, SCOPES, transportFactory, null); credentials.clock = new FixedClock(0L); transport.addServiceAccount(SA_CLIENT_EMAIL, tokenString); AccessToken accessToken = credentials.refreshAccessToken(); assertEquals(tokenString, accessToken.getTokenValue()); assertEquals(3600 * 1000L, accessToken.getExpirationTimeMillis().longValue()); // Test for large expires_in values (should not overflow). transport.setExpiresInSeconds(3600 * 1000); accessToken = credentials.refreshAccessToken(); assertEquals(tokenString, accessToken.getTokenValue()); assertEquals(3600 * 1000 * 1000L, accessToken.getExpirationTimeMillis().longValue()); }
@Test public void equals_true() throws IOException { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken otherAccessToken = new AccessToken(TOKEN, EXPIRATION_DATE); assertTrue(accessToken.equals(otherAccessToken)); assertTrue(otherAccessToken.equals(accessToken)); }
@Test public void serialize() throws IOException, ClassNotFoundException { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken deserializedAccessToken = serializeAndDeserialize(accessToken); assertEquals(accessToken, deserializedAccessToken); assertEquals(accessToken.hashCode(), deserializedAccessToken.hashCode()); assertEquals(accessToken.toString(), deserializedAccessToken.toString()); } }
@Test public void hashCode_equals() throws IOException { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken otherAccessToken = new AccessToken(TOKEN, EXPIRATION_DATE); assertEquals(accessToken.hashCode(), otherAccessToken.hashCode()); }
@Test public void toString_containsFields() { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); String expectedToString = String.format("AccessToken{tokenValue=%s, expirationTimeMillis=%d}", TOKEN, EXPIRATION_DATE.getTime()); assertEquals(expectedToString, accessToken.toString()); }
/** * 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); }
/** * Refresh the access token by getting it from the App Identity service. */ @Override public AccessToken refreshAccessToken() throws IOException { if (createScopedRequired()) { throw new IOException("AppEngineCredentials requires createScoped call before use."); } try { Object accessTokenResult = getAccessTokenResult.invoke(appIdentityService, scopes); String accessToken = (String) getAccessToken.invoke(accessTokenResult); Date expirationTime = (Date) getExpirationTime.invoke(accessTokenResult); return new AccessToken(accessToken, expirationTime); } catch (Exception e) { throw new IOException("Could not get the access token.", e); } }
@Test public void toString_containsFields() throws IOException { AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); UserCredentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) .setClientSecret(CLIENT_SECRET) .setRefreshToken(REFRESH_TOKEN) .setAccessToken(accessToken) .setHttpTransportFactory(transportFactory) .setTokenServerUri(tokenServer) .build(); String expectedToString = String.format( "UserCredentials{requestMetadata=%s, temporaryAccess=%s, clientId=%s, refreshToken=%s, " + "tokenServerUri=%s, transportFactoryClassName=%s}", ImmutableMap.of(AuthHttpConstants.AUTHORIZATION, ImmutableList.of(OAuth2Utils.BEARER_PREFIX + accessToken.getTokenValue())), accessToken.toString(), CLIENT_ID, REFRESH_TOKEN, tokenServer, MockTokenServerTransportFactory.class.getName()); assertEquals(expectedToString, credentials.toString()); }
final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; AccessToken accessToken1 = new AccessToken(accessTokenValue1, new Date(EXPIRATION_TIME)); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); assertEquals(accessTokenValue1, credentials1.getAccessToken().getTokenValue()); assertEquals(accessTokenValue2, credentials1.getAccessToken().getTokenValue()); assertEquals(accessTokenValue2, credentials2.getAccessToken().getTokenValue());
@Test public void getCredentials_storedCredentials_returnsStored() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); UserCredentials initialCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID_VALUE) .setClientSecret(CLIENT_SECRET) .setRefreshToken(REFRESH_TOKEN) .setAccessToken(ACCESS_TOKEN) .build(); UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) .setScopes(SCOPES) .setTokenStore(tokenStore) .build(); authorizer.storeCredentials(USER_ID, initialCredentials); UserCredentials credentials = authorizer.getCredentials(USER_ID); assertEquals(REFRESH_TOKEN, credentials.getRefreshToken()); assertEquals(ACCESS_TOKEN_VALUE, credentials.getAccessToken().getTokenValue()); assertEquals(EXPIRATION_TIME, credentials.getAccessToken().getExpirationTimeMillis()); }
@Test public void equals_false_token() throws IOException { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken otherAccessToken = new AccessToken("otherToken", EXPIRATION_DATE); assertFalse(accessToken.equals(otherAccessToken)); assertFalse(otherAccessToken.equals(accessToken)); }
/** * 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); }