/** * Calls the refreshToken method on credential. * * @throws IOException if the credential could not be refreshed. */ boolean callRefreshToken(Credential credential) throws IOException { return credential.refreshToken(); }
/** * Calls the refreshToken method on credential. * * @throws IOException if the credential could not be refreshed. */ boolean callRefreshToken(Credential credential) throws IOException { return credential.refreshToken(); }
private Request refreshAndSign(Response response, Credential credential) throws IOException { credential.refreshToken(); return resign(response, credential); }
/** * Use the {@link Credential} to request a new access token from the * authorization endpoint. * * @return whether a new access token was successfully retrieved */ public boolean refreshToken() throws AuthenticationException { try { return this.credential.refreshToken(); } catch (IOException e) { AuthenticationException ae = new AuthenticationException("Failed to refresh access token: " + e.getMessage()); ae.initCause(e); throw ae; } } }
// 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 }
/** * 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); }
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; } }
/** * 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"); }
if ( credential.refreshToken() )
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()) { ... }
/** * Initializes OAuth2 credential using preconfigured ServiceAccount settings on the local GCE VM. * See: <a href="https://developers.google.com/compute/docs/authentication">Authenticating from * Google Compute Engine</a>. */ public Credential getCredentialFromMetadataServiceAccount() throws IOException, GeneralSecurityException { logger.atFine().log("getCredentialFromMetadataServiceAccount()"); Credential cred = new ComputeCredentialWithRetry( new ComputeCredential.Builder(getStaticHttpTransport(), JSON_FACTORY) .setRequestInitializer(new CredentialHttpRetryInitializer())); try { cred.refreshToken(); } catch (IOException e) { throw new IOException( "Error getting access token from metadata server at: " + cred.getTokenServerEncodedUrl(), e); } return cred; }
/** * Initializes OAuth2 credential using preconfigured ServiceAccount settings on the local GCE VM. * See: <a href="https://developers.google.com/compute/docs/authentication">Authenticating from * Google Compute Engine</a>. */ public Credential getCredentialFromMetadataServiceAccount() throws IOException, GeneralSecurityException { logger.atFine().log("getCredentialFromMetadataServiceAccount()"); Credential cred = new ComputeCredentialWithRetry( new ComputeCredential.Builder(getStaticHttpTransport(), JSON_FACTORY) .setRequestInitializer(new CredentialHttpRetryInitializer())); try { cred.refreshToken(); } catch (IOException e) { throw new IOException( "Error getting access token from metadata server at: " + cred.getTokenServerEncodedUrl(), e); } return cred; }
boolean tokenRefreshed; try { tokenRefreshed = credential.refreshToken(); } catch (IOException ioEx) { tokenRefreshed = false;