• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

googleapis/google-auth-library-java: Open source Auth client library for Java

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

googleapis/google-auth-library-java

开源软件地址(OpenSource Url):

https://github.com/googleapis/google-auth-library-java

开源编程语言(OpenSource Language):

Java 96.3%

开源软件介绍(OpenSource Introduction):

Google Auth Library

Open source authentication client library for Java.

stable Maven

This project consists of 3 artifacts:

Table of contents:

Quickstart

If you are using Maven, add this to your pom.xml file (notice that you can replace google-auth-library-oauth2-http with any of google-auth-library-credentials and google-auth-library-appengine, depending on your application needs):

<dependency>
  <groupId>com.google.auth</groupId>
  <artifactId>google-auth-library-oauth2-http</artifactId>
  <version>1.3.0</version>
</dependency>

If you are using Gradle, add this to your dependencies

implementation 'com.google.auth:google-auth-library-oauth2-http:1.3.0'

If you are using SBT, add this to your dependencies

libraryDependencies += "com.google.auth" % "google-auth-library-oauth2-http" % "1.3.0"

google-auth-library-oauth2-http

Application Default Credentials

This library provides an implementation of Application Default Credentials for Java. The Application Default Credentials provide a simple way to get authorization credentials for use in calling Google APIs.

They are best suited for cases when the call needs to have the same identity and authorization level for the application independent of the user. This is the recommended approach to authorize calls to Cloud APIs, particularly when you're building an application that uses Google Cloud Platform.

Application Default Credentials also support workload identity federation to access Google Cloud resources from non-Google Cloud platforms including Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). Workload identity federation is recommended for non-Google Cloud environments as it avoids the need to download, manage and store service account private keys locally, see: Workload Identity Federation.

Getting Application Default Credentials

To get Application Default Credentials use GoogleCredentials.getApplicationDefault() or GoogleCredentials.getApplicationDefault(HttpTransportFactory). These methods return the Application Default Credentials which are used to identify and authorize the whole application. The following are searched (in order) to find the Application Default Credentials:

  1. Credentials file pointed to by the GOOGLE_APPLICATION_CREDENTIALS environment variable
  2. Credentials provided by the Google Cloud SDK gcloud auth application-default login command
  3. Google App Engine built-in credentials
  4. Google Cloud Shell built-in credentials
  5. Google Compute Engine built-in credentials
    • Skip this check by setting the environment variable NO_GCE_CHECK=true
    • Customize the GCE metadata server address by setting the environment variable GCE_METADATA_HOST=<hostname>

Explicit Credential Loading

To get Credentials from a Service Account JSON key use GoogleCredentials.fromStream(InputStream) or GoogleCredentials.fromStream(InputStream, HttpTransportFactory). Note that the credentials must be refreshed before the access token is available.

GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("/path/to/credentials.json"));
credentials.refreshIfExpired();
AccessToken token = credentials.getAccessToken();
// OR
AccessToken token = credentials.refreshAccessToken();

ImpersonatedCredentials

Allows a credentials issued to a user or service account to impersonate another. The source project using ImpersonatedCredentials must enable the "IAMCredentials" API. Also, the target service account must grant the orginating principal the "Service Account Token Creator" IAM role.

String credPath = "/path/to/svc_account.json";
ServiceAccountCredentials sourceCredentials = ServiceAccountCredentials
     .fromStream(new FileInputStream(credPath));
sourceCredentials = (ServiceAccountCredentials) sourceCredentials
    .createScoped(Arrays.asList("https://www.googleapis.com/auth/iam"));

ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create(sourceCredentials,
    "[email protected]", null,
    Arrays.asList("https://www.googleapis.com/auth/devstorage.read_only"), 300);

Storage storage_service = StorageOptions.newBuilder().setProjectId("project-id")
    .setCredentials(targetCredentials).build().getService();

for (Bucket b : storage_service.list().iterateAll())
    System.out.println(b); 

Workload Identity Federation

Using workload identity federation, your application can access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure, or any identity provider that supports OpenID Connect (OIDC).

Traditionally, applications running outside Google Cloud have used service account keys to access Google Cloud resources. Using identity federation, your workload can impersonate a service account. This lets the external workload access Google Cloud resources directly, eliminating the maintenance and security burden associated with service account keys.

Accessing resources from AWS

In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements are needed:

  • A workload identity pool needs to be created.
  • AWS needs to be added as an identity provider in the workload identity pool (the Google organization policy needs to allow federation from AWS).
  • Permission to impersonate a service account needs to be granted to the external identity.

Follow the detailed instructions on how to configure workload identity federation from AWS.

After configuring the AWS provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file contains non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.

To generate the AWS workload identity configuration, run the following command:

# Generate an AWS configuration file.
gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \
    --service-account $SERVICE_ACCOUNT_EMAIL \
    --aws \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $AWS_PROVIDER_ID: The AWS provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.

This generates the configuration file in the specified output file.

If you want to use the AWS IMDSv2 flow, you can add the field below to the credential_source in your AWS ADC configuration file: "imdsv2_session_token_url": "http://169.254.169.254/latest/api/token"

The gcloud create-cred-config command will be updated to support this soon.

You can now use the Auth library to call Google Cloud resources from AWS.

Access resources from Microsoft Azure

In order to access Google Cloud resources from Microsoft Azure, the following requirements are needed:

  • A workload identity pool needs to be created.
  • Azure needs to be added as an identity provider in the workload identity pool (the Google organization policy needs to allow federation from Azure).
  • The Azure tenant needs to be configured for identity federation.
  • Permission to impersonate a service account needs to be granted to the external identity.

Follow the detailed instructions on how to configure workload identity federation from Microsoft Azure.

After configuring the Azure provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file contains non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.

To generate the Azure workload identity configuration, run the following command:

# Generate an Azure configuration file.
gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AZURE_PROVIDER_ID \
    --service-account $SERVICE_ACCOUNT_EMAIL \
    --azure \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $AZURE_PROVIDER_ID: The Azure provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.

This generates the configuration file in the specified output file.

You can now use the Auth library to call Google Cloud resources from Azure.

Accessing resources from an OIDC identity provider

In order to access Google Cloud resources from an identity provider that supports OpenID Connect (OIDC), the following requirements are needed:

  • A workload identity pool needs to be created.
  • An OIDC identity provider needs to be added in the workload identity pool (the Google organization policy needs to allow federation from the identity provider).
  • Permission to impersonate a service account needs to be granted to the external identity.

Follow the detailed instructions on how to configure workload identity federation from an OIDC identity provider.

After configuring the OIDC provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file contains non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.

For OIDC providers, the Auth library can retrieve OIDC tokens either from a local file location (file-sourced credentials) or from a local server (URL-sourced credentials).

File-sourced credentials For file-sourced credentials, a background process needs to be continuously refreshing the file location with a new OIDC token prior to expiration. For tokens with one hour lifetimes, the token needs to be updated in the file every hour. The token can be stored directly as plain text or in JSON format.

To generate a file-sourced OIDC configuration, run the following command:

# Generate an OIDC configuration file for file-sourced credentials.
gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \
    --service-account $SERVICE_ACCOUNT_EMAIL \
    --credential-source-file $PATH_TO_OIDC_ID_TOKEN \
    # Optional arguments for file types. Default is "text":
    # --credential-source-type "json" \
    # Optional argument for the field that contains the OIDC credential.
    # This is required for json.
    # --credential-source-field-name "id_token" \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $OIDC_PROVIDER_ID: The OIDC provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.
  • $PATH_TO_OIDC_ID_TOKEN: The file path used to retrieve the OIDC token.

This generates the configuration file in the specified output file.

URL-sourced credentials For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. The response can be in plain text or JSON. Additional required request headers can also be specified.

To generate a URL-sourced OIDC workload identity configuration, run the following command:

# Generate an OIDC configuration file for URL-sourced credentials.
gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \
    --service-account $SERVICE_ACCOUNT_EMAIL \
    --credential-source-url $URL_TO_GET_OIDC_TOKEN \
    --credential-source-headers $HEADER_KEY=$HEADER_VALUE \
    # Optional arguments for file types. Default is "text":
    # --credential-source-type "json" \
    # Optional argument for the field that contains the OIDC credential.
    # This is required for json.
    # --credential-source-field-name "id_token" \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $OIDC_PROVIDER_ID: The OIDC provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.
  • $URL_TO_GET_OIDC_TOKEN: The URL of the local server endpoint to call to retrieve the OIDC token.
  • $HEADER_KEY and $HEADER_VALUE: The additional header key/value pairs to pass along the GET request to $URL_TO_GET_OIDC_TOKEN, e.g. Metadata-Flavor=Google.

You can now use the Auth library to call Google Cloud resources from an OIDC provider.

Using External Identities

External identities (AWS, Azure, and OIDC-based providers) can be used with Application Default Credentials. In order to use external identities with Application Default Credentials, you need to generate the JSON credentials configuration file for your external identity as described above. Once generated, store the path to this file in the GOOGLE_APPLICATION_CREDENTIALS environment variable.

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/config.json

The library can now choose the right type of client and initialize credentials from the context provided in the configuration file.

GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault();

String projectId = "your-project-id";
String url = "https://storage.googleapis.com/storage/v1/b?project=" + projectId;

HttpCredentialsAdapter credentialsAdapter = new HttpCredentialsAdapter(googleCredentials);
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory(credentialsAdapter);
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(url));

JsonObjectParser parser = new JsonObjectParser(GsonFactory.getDefaultInstance());
request.setParser(parser);

HttpResponse response = request.execute();
System.out.println(response.parseAsString());

You can also explicitly initialize external account clients using the generated configuration file.

ExternalAccountCredentials credentials = 
    ExternalAccountCredentials.fromStream(new FileInputStream("/path/to/credentials.json"));

Downscoping with Credential Access Boundaries

Downscoping with Credential Access Boundaries enables the ability to downscope, or restrict, the Identity and Access Management (IAM) permissions that a short-lived credential can use for Cloud Storage.

The DownscopedCredentials class can be used to produce a downscoped access token from a CredentialAccessBoundary and a source credential. The Credential Access Boundary specifies which resources the newly created credential can access, as well as an upper bound on the permissions that are available on each resource. Using downscoped credentials ensures tokens in flight always have the least privileges (Principle of Least Privilege).

The snippet below shows how to initialize a CredentialAccessBoundary with one AccessBoundaryRule which specifies that the downscoped token will have readonly access to objects starting with "customer-a" in bucket "bucket-123":

// Create the AccessBoundaryRule.
String availableResource = "//storage.googleapis.com/projects/_/buckets/bucket-123";
String availablePermission = "inRole:roles/storage.objectViewer";
String expression =  "resource.name.startsWith('projects/_/buckets/bucket-123/objects/customer-a')";

CredentialAccessBoundary.AccessBoundaryRule rule =
    CredentialAccessBoundary.AccessBoundaryRule.newBuilder()
        .setAvailableResource(availableResource)
        .addAvailablePermission(availablePermission)
        .setAvailabilityCondition(
        CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition.newBuilder().setExpression(expression).build())
        .build();

// Create the CredentialAccessBoundary with the rule.
CredentialAccessBoundary credentialAccessBoundary = 
        CredentialAccessBoundary.newBuilder().addRule(rule).build();

The common pattern of usage is to have a token broker with elevated access generate these downscoped credentials from higher access source credentials and pass the downscoped short-lived access tokens to a token consumer via some secure authenticated channel for limited access to Google Cloud Storage resources.

Using the CredentialAccessBoundary created above in the Token Broker:

// Retrieve the source credentials from ADC.
GoogleCredentials sourceCredentials = GoogleCredentials.getApplicationDefault()
        .createScoped("https://www.googleapis.com/auth/cloud-platform");

// Initialize the DownscopedCredentials class.
DownscopedCredentials downscopedCredentials =
    DownscopedCredentials.newBuilder()
        .setSourceCredential(credentials)
        .setCredentialAccessBoundary(credentialAccessBoundary)
        .build();

// Retrieve the downscoped access token.
// This will need to be passed to the Token Consumer.
AccessToken downscopedAccessToken = downscopedCredentials.refreshAccessToken();

A token broker can be set up on a server in a private network. Various workloads (token consumers) in the same network will send authenticated requests to that broker for downscoped tokens to access or modify specific google cloud storage buckets.

The broker will instantiate downscoped credentials instances that can be used to generate short lived downscoped access tokens which will be passed to the token consumer.

Putting it all together:

// Retrieve the source credentials from ADC.
GoogleCredentials sourceCredentials = GoogleCredentials.getApplicationDefault()
        .createScoped("https://www.googleapis.com/auth/cloud-platform");

// Create an Access Boundary Rule which will restrict the downscoped token to having readonly
// access to objects starting with "customer-a" in bucket "bucket-123".
String availableResource = "//storage.googleapis.com/projects/_/buckets/bucket-123";
String availablePermission = "inRole:roles/storage.objectViewer";
String expression =  "resource.name.startsWith('projects/_/buckets/bucket-123/objects/customer-a')";
        
CredentialAccessBoundary.AccessBoundaryRule rule =
    CredentialAccessBoundary.AccessBoundaryRule.newBuilder()
        .setAvailableResource(availableResource)
        .addAvailablePermission(availablePermission)
        .setAvailabilityCondition(
            new AvailabilityCondition(expression, /* title= */ null, /* description= */ null))
        .build();

// Initialize the DownscopedCredentials class.
DownscopedCredentials downscopedCredentials =
    DownscopedCredentials.newBuilder()
        .setSourceCredential(credentials)
        .setCredentialAccessBoundary(CredentialAccessBoundary.newBuilder().addRule(rule).build())
        .build();

// Retrieve the downscoped access token.
// This will need to be passed to the Token Consumer.
AccessToken downscopedAccessToken = downscopedCredentials.refreshAccessToken();

These downscoped access tokens can be used by the Token Consumer via OAuth2Credentials or OAuth2CredentialsWithRefresh. This credential can then be used to initialize a storage client instance to access Google Cloud Storage resources with restricted access.

// 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() {
      // Add the logic here that retrieves the token from your Token Broker.
      return accessToken;
    }
};

// Downscoped token retrieved from token broker.
AccessToken downscopedToken = handler.refreshAccessToken();

// Build the OAuth2CredentialsWithRefresh from the downscoped token and pass a refresh handler 
// to handle token expiration. Passing the original downscoped token or the expiry here is optional,
// as the refresh_handler will generate the downscoped token on demand.
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 GCS APIs.
// Since we passed the downscoped credential, we will have have limited readonly access to objects
// starting with "customer-a" in bucket "bucket-123".
storage.get(...)

Note: Only Cloud Storage supports Credential Access Boundaries. Other Google Cloud services do not support this feature.

Configuring a Proxy

For HTTP clients, a basic proxy can be configured by using http.proxyHost and related system properties as documented by Java Networking and Proxies.

For a more custom proxy (e.g. for an authenticated proxy), provide a custom HttpTransportFactory to GoogleCredentials:

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.apache.v2.ApacheHttpTransport;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.GoogleCredentials;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;

import java.io.IOException;

public class ProxyExample {
  public GoogleCredentials getCredentials() throws IOException {
    HttpTransportFactory httpTransportFactory = getHttpTransportFactory(
        "some-host", 8080, "some-username", "some-password"
    );

    return GoogleCredentials.getApplicationDefault(httpTransportFactory);
  }

  public HttpTransportFactory getHttpTransportFactory(String proxyHost, int proxyPort, String proxyUsername, String proxyPassword) {
    
                      

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap