/** * 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; } }
/** * 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; } }
// 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 }
private String getCurrentUserAccessToken(OneDriveBlobProvider provider) throws IOException { Optional<NuxeoOAuth2Token> nuxeoToken = getCurrentNuxeoToken(provider); if (nuxeoToken.isPresent()) { // Here we don't need to handle NuxeoException as we just retrieved the token Credential credential = provider.getCredential(nuxeoToken.get().getServiceLogin()); Long expiresInSeconds = credential.getExpiresInSeconds(); if (expiresInSeconds != null && expiresInSeconds > 0) { return credential.getAccessToken(); } } return ""; }
void refreshAccessToken() { final Credential credential = config.getCredential(); final Long expiresIn = credential.getExpiresInSeconds(); // trigger refresh if token is null or is about to expire if (credential.getAccessToken() == null || expiresIn != null && expiresIn <= 60) { try { credential.refreshToken(); } catch (final IOException e) { log.error("Storage exception", Throwables.getRootCause(e)); } } // update local token if the credentials token has refreshed since last update final String accessTokenLocal = credential.getAccessToken(); if (this.accessToken == null || !accessToken.equals(accessTokenLocal)) { this.accessToken = accessTokenLocal; } }
/** * Retrieves a valid access token for a given provider and the current user. If expired, the token will be * refreshed. */ @GET @Path("provider/{providerId}/token") public Response getToken(@PathParam("providerId") String providerId, @Context HttpServletRequest request) throws IOException { NuxeoOAuth2ServiceProvider provider = getProvider(providerId); String username = request.getUserPrincipal().getName(); NuxeoOAuth2Token token = getToken(provider, username); if (token == null) { return Response.status(Status.NOT_FOUND).build(); } Credential credential = getCredential(provider, token); if (credential == null) { return Response.status(Status.NOT_FOUND).build(); } Long expiresInSeconds = credential.getExpiresInSeconds(); if (expiresInSeconds != null && expiresInSeconds <= 0) { credential.refreshToken(); } Map<String, Object> result = new HashMap<>(); result.put("token", credential.getAccessToken()); return buildResponse(Status.OK, result); }
/** * 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; } }
// FileDataStoreFactory is used to create new credentials and // simultaneously loads previously generated credentials from a file // Specify a location where the file should be stored via DIRECTORY // The file is automatically generated and encrypted FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(DIRECTORY)); // Create the GoogleAuthorizationCodeFlow. This is needed to get the user (you?) // approval (you need that so you can access data). getClientSecrets() returns a // GoogleClientSecrets. If you want to, I can provide some code :) // Here you also specify your scopes GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, getClientSecrets(), Arrays.asList(scope)) .setCredentialDataStore(StoredCredential.getDefaultDataStore(fileDataStoreFactory)).build(); // With the GoogleAuthorizationCodeFlow you can create a Credential Credential cred = flow.loadCredential("user"); // Check if the cred is null or expired (credentials last about an hour I think) if(cred == null || (cred.getExpiresInSeconds() < 100 && !cred.refreshToken())){ // If it is expired, you need to refresh it via UserAuthorization, again, if you // want to I can provide an example code GoogleTokenResponse resp = getUserAuthorization(flow); if(resp == null){ return null; } cred = flow.createAndStoreCredential(resp, "user"); }
Long expiresIn = credential.getExpiresInSeconds();
/** * 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(); } }
return null; final Long expirationTime = credential.getExpiresInSeconds(); if (expirationTime != null && expirationTime < 0) { boolean tokenRefreshed;
@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()); }
@Test public void authenticate() throws Exception { String authorizationCode = "authorizationCode"; String expectedRequestContent = "code=authorizationCode&grant_type=authorization_code" + "&redirect_uri=http%3A%2F%2Fredirect&scope=profile+request" + "&client_id=CLIENT_ID&client_secret=CLIENT_SECRET"; OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("http://redirect") .setHttpTransport(mockHttpTransport) .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST)) .build(); Credential credential = oAuth2Credentials.authenticate(authorizationCode, "userId"); assertEquals("Request URL did not match.", TOKEN_REQUEST_URL, mockHttpTransport.lastRequestUrl); assertEquals("Request content did not match.", expectedRequestContent, mockHttpTransport.lastRequestContent); 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()); }
@Test public void authenticate_whenThereAreNoScopes() throws Exception { String authorizationCode = "authorizationCode"; String expectedRequestContent = "code=authorizationCode&grant_type=authorization_code" + "&redirect_uri=http%3A%2F%2Fredirect" + "&client_id=CLIENT_ID&client_secret=CLIENT_SECRET"; OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("http://redirect") .setHttpTransport(mockHttpTransport) .build(); Credential credential = oAuth2Credentials.authenticate(authorizationCode, "userId"); assertEquals("Request URL did not match.", TOKEN_REQUEST_URL, mockHttpTransport.lastRequestUrl); assertEquals("Request content did not match.", expectedRequestContent, mockHttpTransport.lastRequestContent); 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()); }
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", 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",