private synchronized Storage getService() throws IOException, GeneralSecurityException { logger.trace("Getting Google Cloud Storage service"); // leave this here for tests because they do things like manipulate properties dynamically to test invalid values this.bucketName = properties.getProperty( "usergrid.binary.bucketname" ); if (instance == null) { // Google provides different authentication types which are different based on if the application is // running within GCE(Google Compute Engine) or GAE (Google App Engine). If Usergrid is running in // GCE or GAE, the SDK will automatically authenticate and get access to // cloud storage. Else, the full path to a credential file should be provided in the following environment variable // // GOOGLE_APPLICATION_CREDENTIALS // // The SDK will attempt to load the credential file for a service account. See the following // for more info: https://developers.google.com/identity/protocols/application-default-credentials#howtheywork GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(StorageScopes.all()); final TransportOptions transportOptions = HttpTransportOptions.newBuilder() .setConnectTimeout(30000) // in milliseconds .setReadTimeout(30000) // in milliseconds .build(); instance = StorageOptions.newBuilder() .setCredentials(credentials) .setTransportOptions(transportOptions) .build() .getService(); } return instance; }
if (file.exists()) { try (final FileInputStream s = new FileInputStream(file)) { credentials = GoogleCredentials.fromStream(s); LOG.info("Using Google Credentials from file: " + file.getAbsolutePath()); credentials = GoogleCredentials.getApplicationDefault(); LOG.info("Using Google Application Default Credentials"); return scopes.isEmpty() ? credentials : credentials.createScoped(scopes);
/** Returns the authentication credentials. If required, credentials are scoped. */ public Credentials getScopedCredentials() { Credentials credentialsToReturn = credentials; if (credentials instanceof GoogleCredentials && ((GoogleCredentials) credentials).createScopedRequired()) { credentialsToReturn = ((GoogleCredentials) credentials).createScoped(getScopes()); } return credentialsToReturn; }
private GoogleCredentials loadGoogleCredentials( final boolean useDefaultCredentials, final File credentialsFile) throws ArgumentParserException, IOException { if (useDefaultCredentials && credentialsFile != null) { final String msg = String.format("Cannot set both %s and %s", this.googleCloudCredentialsFile.getDest(), this.useGoogleDefaultApplicationCredentials.getDest()); throw new IllegalArgumentException(msg); } if (useDefaultCredentials) { return GoogleCredentials.getApplicationDefault(); } try (final FileInputStream stream = new FileInputStream(credentialsFile)) { return GoogleCredentials.fromStream(stream); } }
static void authExplicit(String jsonPath) throws IOException { // You can specify a credential file by providing a path to GoogleCredentials. // Otherwise credentials are read from the GOOGLE_APPLICATION_CREDENTIALS environment variable. GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath)) .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform")); Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService(); System.out.println("Buckets:"); Page<Bucket> buckets = storage.list(); for (Bucket bucket : buckets.iterateAll()) { System.out.println(bucket.toString()); } } // [END auth_cloud_explicit]
private static GoogleCredentials defaultCredentials() { try { return GoogleCredentials.getApplicationDefault(); } catch (Exception ex) { return null; } }
/** * Constructs a ContainerRegistryAuthSupplier for the account with the given credentials. * * @see Builder */ public static Builder fromStream(final InputStream credentialsStream) throws IOException { final GoogleCredentials credentials = GoogleCredentials.fromStream(credentialsStream); return new Builder(credentials); }
private static Credentials getDefaultCredential() { GoogleCredentials credential; try { credential = GoogleCredentials.getApplicationDefault(); } catch (IOException e) { throw new RuntimeException("Failed to get application default credential.", e); } if (credential.createScopedRequired()) { Collection<String> bigqueryScope = Lists.newArrayList(BigqueryScopes.all()); credential = credential.createScoped(bigqueryScope); } return credential; }
public ContainerRegistryAuthSupplier build() { final GoogleCredentials credentials = this.credentials.createScoped(scopes); // log some sort of identifier for the credentials, which requires looking at the // instance type if (credentials instanceof ServiceAccountCredentials) { final String clientEmail = ((ServiceAccountCredentials) credentials).getClientEmail(); log.info("loaded credentials for service account with clientEmail={}", clientEmail); } else if (credentials instanceof UserCredentials) { final String clientId = ((UserCredentials) credentials).getClientId(); log.info("loaded credentials for user account with clientId={}", clientId); } final Clock clock = Clock.systemDefaultZone(); final DefaultCredentialRefresher refresher = new DefaultCredentialRefresher(); return new ContainerRegistryAuthSupplier(credentials, clock, minimumExpiryMillis, refresher); } }
@Test public void createdScoped_enablesAccessTokens() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8(SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, null, transportFactory, null); try { credentials.getRequestMetadata(CALL_URI); fail("Should not be able to get token without scopes"); } catch (Exception expected) { // Expected } GoogleCredentials scopedCredentials = credentials.createScoped(SCOPES); Map<String, List<String>> metadata = scopedCredentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); }
public GoogleCredentials getFirebaseCredentials() { try { if (firebaseCredentials == null) { try { firebaseCredentials = GoogleCredentials.fromStream( new ByteArrayInputStream(firebase.toString().getBytes("utf-8"))) .createScoped(FIREBASE_SCOPES); } catch (UnsupportedEncodingException e) { // Should never happen. } } firebaseCredentials.refreshIfExpired(); } catch (IOException e) { throw new RuntimeException("Should never happen.", e); } return firebaseCredentials; }
@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 fromStream_serviceAccount_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = ServiceAccountCredentialsTest .writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccountStream, transportFactory); assertNotNull(credentials); credentials = credentials.createScoped(SCOPES); Map<String, List<String>> metadata = credentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); }
@Override public AccessToken refreshAccessToken() throws IOException { if (this.sourceCredentials.getAccessToken() == null) { this.sourceCredentials = this.sourceCredentials .createScoped(Arrays.asList(CLOUD_PLATFORM_SCOPE)); this.sourceCredentials.refreshIfExpired(); } catch (IOException e) { throw new IOException("Unable to refresh sourceCredentials", e);
@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)); } } }
@Test public void fromStream_user_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(USER_CLIENT_ID, USER_CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); InputStream userStream = UserCredentialsTest.writeUserStream(USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN); GoogleCredentials credentials = GoogleCredentials.fromStream(userStream, transportFactory); assertNotNull(credentials); Map<String, List<String>> metadata = credentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); }
@Override public Optional<AccessToken> get() { Optional<AccessToken> tokenOpt = Optional.absent(); if (enabled) { if (staticToken != null) { tokenOpt = Optional.of(staticToken); } else { try { synchronized (lock) { if (credentials == null) { credentials = getCredentialsWithScopes(tokenScopes); } credentials.refreshIfExpired(); } tokenOpt = Optional.of(credentials.getAccessToken()); } catch (IOException | RuntimeException e) { LOG.debug("Exception (possibly benign) while loading Google Credentials", e); return Optional.absent(); } } } return tokenOpt; }
@Override public void getToken(boolean forceRefresh, final GetTokenCompletionListener listener) { try { if (forceRefresh) { credentials.refresh(); } // The typical way to use a GoogleCredentials instance is to call its getRequestMetadata(), // and include the metadata in your request. Since we are accessing the token directly via // getAccessToken(), we must first call getRequestMetadata() to ensure the token is available // (refreshed if necessary). credentials.getRequestMetadata(); AccessToken accessToken = credentials.getAccessToken(); listener.onSuccess(wrapOAuthToken(accessToken, authVariable)); } catch (Exception e) { listener.onError(e.toString()); } }
/** * Get an accessToken to use, possibly refreshing the token if it expires within the * minimumExpiryMillis. */ private AccessToken getAccessToken() throws IOException { // synchronize attempts to refresh the accessToken synchronized (credentials) { if (needsRefresh(credentials.getAccessToken())) { credentialRefresher.refresh(credentials); } } return credentials.getAccessToken(); }
@Test public void createScopedRequired_emptyScopes_true() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, EMPTY_SCOPES); assertTrue(credentials.createScopedRequired()); }