Search in sources :

Example 1 with OAuth2CredentialsWithRefresh

use of com.google.auth.oauth2.OAuth2CredentialsWithRefresh in project java-docs-samples by GoogleCloudPlatform.

the class DownscopingExample method tokenConsumer.

// [END auth_downscoping_token_broker]
/**
 * Simulates token consumer readonly access to the specified object.
 */
// [START auth_downscoping_token_consumer]
public static void tokenConsumer(final String bucketName, final String objectName) throws IOException {
    // You can pass an `OAuth2RefreshHandler` to `OAuth2CredentialsWithRefresh` which will allow the
    // library to seamlessly handle downscoped token refreshes on expiration.
    OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() {

        @Override
        public AccessToken refreshAccessToken() throws IOException {
            // resources in the bucket is needed, this mechanism can be used.
            return getTokenFromBroker(bucketName, objectName.substring(0, 3));
        }
    };
    // Downscoped token retrieved from token broker.
    AccessToken downscopedToken = handler.refreshAccessToken();
    // Create the OAuth2CredentialsWithRefresh from the downscoped token and pass a refresh handler
    // which will handle token expiration.
    // This will allow the consumer to seamlessly obtain new downscoped tokens on demand every time
    // token expires.
    OAuth2CredentialsWithRefresh credentials = OAuth2CredentialsWithRefresh.newBuilder().setAccessToken(downscopedToken).setRefreshHandler(handler).build();
    // Use the credentials with the Cloud Storage SDK.
    StorageOptions options = StorageOptions.newBuilder().setCredentials(credentials).build();
    Storage storage = options.getService();
    // Call Cloud Storage APIs.
    Blob blob = storage.get(bucketName, objectName);
    String content = new String(blob.getContent());
    System.out.println("Retrieved object, " + objectName + ", from bucket," + bucketName + ", with content: " + content);
}
Also used : Blob(com.google.cloud.storage.Blob) Storage(com.google.cloud.storage.Storage) StorageOptions(com.google.cloud.storage.StorageOptions) AccessToken(com.google.auth.oauth2.AccessToken) OAuth2CredentialsWithRefresh(com.google.auth.oauth2.OAuth2CredentialsWithRefresh)

Aggregations

AccessToken (com.google.auth.oauth2.AccessToken)1 OAuth2CredentialsWithRefresh (com.google.auth.oauth2.OAuth2CredentialsWithRefresh)1 Blob (com.google.cloud.storage.Blob)1 Storage (com.google.cloud.storage.Storage)1 StorageOptions (com.google.cloud.storage.StorageOptions)1