private String generateParamsString(Optional<Map<String, String>> params) { Map<String, String> updatedParams = new ArrayMap<>(); if (params.isPresent()) { updatedParams.putAll(params.get()); } if (!updatedParams.containsKey(ACCESS_TOKEN_KEY)) { updatedParams.put(ACCESS_TOKEN_KEY, credential.getAccessToken()); } List<String> orderedKeys = updatedParams.keySet().stream().collect(Collectors.toList()); Collections.sort(orderedKeys); List<String> paramStrings = new ArrayList<>(); for (String key : orderedKeys) { String k = key.trim(); String v = updatedParams.get(key).trim(); paramStrings.add(k + "=" + v); } return String.join("&", paramStrings); }
public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException { Map<String, List<String>> map = new HashMap<String, List<String>>(); List<String> list = new ArrayList<String>(); list.add("Bearer " + credential.getAccessToken()); map.put("Authorization", list); return map; } public boolean hasRequestMetadata() { return true; }
public static void main(String[] args) { try { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); // authorization Credential credential = authorize(); // set up global Oauth2 instance oauth2 = new Oauth2.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName( APPLICATION_NAME).build(); // run commands tokenInfo(credential.getAccessToken()); userInfo(); // success! return; } catch (IOException e) { System.err.println(e.getMessage()); } catch (Throwable t) { t.printStackTrace(); } System.exit(1); }
System.out.println("Access token: " + credential.getAccessToken()); request.addHeader("Authorization", "Bearer " + credential.getAccessToken()); request.addHeader("Content-Type", "image/jpeg"); request.addHeader("x-Goog-Upload-protocol", "raw");
/** * Returns the authorization header using the user's OAuth 2.0 credentials. * * @param requestUrl the URL being requested * @param requestMethod the HTTP method of the request * @return the authorization header to be used for the request */ public String getAuthorizationHeader(URL requestUrl, String requestMethod) { return HEADER_PREFIX + this.credential.getAccessToken(); }
private static String createBearerToken(Credential credential) { return String.format(HEADER_BEARER_ACCESS_VALUE, credential.getAccessToken()); }
/** * Gets the OAuth2 authorization header for the parameters and request URL. * * @param oAuth2Compatible exposes the OAuth2 credentials * @return the {@code Authorization} header value to set */ public String getOAuth2AuthorizationHeader(OAuth2Compatible oAuth2Compatible) { return HEADER_PREFIX + oAuth2Compatible.getOAuth2Credential().getAccessToken(); } }
/** * Gets the OAuth2 authorization header for the parameters and request URL. * * @param oAuth2Compatible exposes the OAuth2 credentials * @return the {@code Authorization} header value to set */ public String getOAuth2AuthorizationHeader(OAuth2Compatible oAuth2Compatible) { return HEADER_PREFIX + oAuth2Compatible.getOAuth2Credential().getAccessToken(); } }
public void store(Credential credential) { this.credential = Optional.of(credential); Properties properties = new Properties(); properties.setProperty(PROP_ACCESS_TOKEN, credential.getAccessToken()); properties.setProperty(PROP_REFRESH_TOKEN, credential.getRefreshToken()); try { File file = getAuthenticationFile(options); properties.store(new FileWriter(file), "Properties of jdrivesync."); } catch (IOException e) { throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to store properties file: " + e.getMessage(), e); } }
/** * 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; } }
/** * 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; } }
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; } }
protected OneDriveAPI getOneDriveAPI(Credential credential) { return getOAuth2Provider().getAPIInitializer().apply(credential.getAccessToken()); }
/** * Store information from the credential. * * @param credential credential whose {@link Credential#getAccessToken access token}, * {@link Credential#getRefreshToken refresh token}, and * {@link Credential#getExpirationTimeMilliseconds expiration time} need to be stored */ void store(Credential credential) { accessToken = credential.getAccessToken(); refreshToken = credential.getRefreshToken(); expirationTimeMillis = credential.getExpirationTimeMilliseconds(); }
/** * Store information from the credential. * * @param credential credential whose {@link Credential#getAccessToken access token}, * {@link Credential#getRefreshToken refresh token}, and * {@link Credential#getExpirationTimeMilliseconds expiration time} need to be stored */ void store(Credential credential) { accessToken = credential.getAccessToken(); refreshToken = credential.getRefreshToken(); expirationTimeMillis = credential.getExpirationTimeMilliseconds(); }
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 ""; }
@Override public void store(String userId, Credential credential) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity entity = new Entity(KIND, userId); entity.setProperty("accessToken", credential.getAccessToken()); entity.setProperty("refreshToken", credential.getRefreshToken()); entity.setProperty("expirationTimeMillis", credential.getExpirationTimeMilliseconds()); datastore.put(entity); }
public OneDriveCredential(Credential credential, String businessResource) { super(new Credential.Builder(credential.getMethod()).setTransport(credential.getTransport()) .setJsonFactory(credential.getJsonFactory()) .setTokenServerEncodedUrl( credential.getTokenServerEncodedUrl()) .setClientAuthentication( credential.getClientAuthentication()) .setRequestInitializer(credential.getRequestInitializer()) .setRefreshListeners(credential.getRefreshListeners()) .setClock(credential.getClock())); setAccessToken(credential.getAccessToken()); setRefreshToken(credential.getRefreshToken()); setExpirationTimeMilliseconds(credential.getExpirationTimeMilliseconds()); this.businessResource = Objects.requireNonNull(businessResource); }
@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()); }