### Install oauth2l on Linux/macOS Source: https://context7.com/google/oauth2l/llms.txt Download and extract the pre-compiled binary for Linux or install via Homebrew on macOS. Ensure Go 1.10.3+ is installed for building from source. ```bash # Download and extract for Linux (amd64) curl -O https://storage.googleapis.com/oauth2l/latest/linux_amd64.tgz tar -xzf linux_amd64.tgz sudo mv oauth2l /usr/local/bin/ ``` ```bash # macOS via Homebrew brew install oauth2l ``` ```bash # Docker docker run -it gcr.io/oauth2l/oauth2l header cloud-platform ``` ```bash # Build from source (requires Go 1.10.3+) git clone https://github.com/google/oauth2l cd oauth2l make dev # Binary installed to $GOPATH/bin/oauth2l ``` -------------------------------- ### Build and Install oauth2l Locally Source: https://github.com/google/oauth2l/blob/master/README.md Clone the repository and build the oauth2l tool locally. Ensure Go 1.10.3 or higher is installed. The tool will be installed into your $GOPATH/bin directory. ```bash # Get the package from Github $ git clone https://github.com/google/oauth2l $ cd oauth2l # Install the package into your $GOPATH/bin/ $ make dev # Fetch the access token from your credentials with cloud-platform scope $ ~/go/bin/oauth2l fetch --credentials ~/your_credentials.json --scope cloud-platform # Or you can run if you $GOPATH/bin is already in your $PATH $ oauth2l fetch --credentials ~/your_credentials.json --scope cloud-platform ``` -------------------------------- ### Get Help Information Source: https://github.com/google/oauth2l/blob/master/README.md Use the `--help` flag to display help messages for the main program or specific commands. ```bash $ oauth2l --help ``` ```bash $ oauth2l fetch --help ``` -------------------------------- ### Custom SSO CLI execution example Source: https://context7.com/google/oauth2l/llms.txt Demonstrates the expected interface for a custom SSO CLI tool, showing how it should be invoked with email and scope arguments. ```bash # Custom SSO CLI interface expected: # /usr/bin/sso ... $ /usr/bin/sso me@example.com https://www.googleapis.com/auth/cloud-platform ``` -------------------------------- ### Install oauth2l via Homebrew Source: https://github.com/google/oauth2l/blob/master/README.md Use this command to install oauth2l on Mac OS X using Homebrew. Note that new releases might have a propagation delay. ```bash $ brew install oauth2l ``` -------------------------------- ### Shell Script Integration (Bash) Source: https://context7.com/google/oauth2l/llms.txt Example of how to integrate oauth2l into a bash script for automated Google API access in CI/CD pipelines. ```bash #!/usr/bin/env bash set -euo pipefail PROJECT_ID="my-gcp-project" CREDENTIALS="service_account.json" ``` -------------------------------- ### Custom SSO CLI Interface Example Source: https://github.com/google/oauth2l/blob/master/README.md Illustrates the expected interface for a custom SSO CLI. It takes an email and space-delimited scopes as arguments. ```bash $ /usr/bin/sso me@example.com scope1 scope2 ``` -------------------------------- ### Launch OAuth2l Playground Web App Source: https://context7.com/google/oauth2l/llms.txt Deploys and launches the OAuth2l Playground web application using Docker. Requires Docker to be installed. This feature is experimental. ```bash # Launch OAuth2l Playground (installs on first run) $ oauth2l web ``` ```bash # Launch with a custom installation directory $ oauth2l web --directory /opt/oauth2l-web ``` ```bash # Stop the running web app $ oauth2l web --stop ``` ```bash # Stop from a custom directory $ oauth2l web --stop --directory /opt/oauth2l-web ``` -------------------------------- ### Specify Directory for OAuth2l-web Packages Source: https://github.com/google/oauth2l/blob/master/README.md The `--directory` option for the `web` command allows you to specify a custom directory for installing OAuth2l-web packages. This setting must be reapplied for subsequent executions of the `web` command, including stopping and restarting the app. ```bash $ oauth2l web --directory your/new/directory ``` -------------------------------- ### Fetch Token with OAuth Client ID (3LO) Source: https://context7.com/google/oauth2l/llms.txt Performs 3-legged OAuth (3LO) using an OAuth Client ID JSON. Requires user browser consent. For loopback `redirect_uri`, oauth2l starts a local server to capture the authorization code. ```bash # 3LO: OAuth Client ID (opens browser for user consent) # Credential file must have redirect_uri: http://localhost or urn:ietf:wg:oauth:2.0:oob $ oauth2l fetch \ --type oauth \ --credentials ~/client_credentials.json \ --scope cloud-platform,userinfo.email # Opens browser... user approves... token printed: ya29.zyxwvutsrqpnmolkjihgfedcba ``` ```bash # 3LO with refresh: reuse cached token by refreshing it when expired $ oauth2l fetch \ --credentials ~/client_credentials.json \ --scope cloud-platform \ --refresh ``` ```bash # 3LO loopback: disable auto browser open, set custom timeout $ oauth2l fetch \ --credentials ~/client_credentials.json \ --disableAutoOpenConsentPage \ --consentPageInteractionTimeout 120 \ --consentPageInteractionTimeoutUnits seconds \ --scope cloud-platform # Prints consent URL for manual navigation ``` -------------------------------- ### Specify Curl CLI Path Source: https://github.com/google/oauth2l/blob/master/README.md Optionally provide the path to the curl CLI executable using `--curlcli` for the `curl` command. This is useful for specifying a custom curl installation. ```bash $ oauth2l curl --curlcli /usr/bin/curl --type sso --email me@google.com --scope cloud-platform --url https://pubsub.googleapis.com/v1/projects/my-project-id/topics ``` -------------------------------- ### Get Authorization Header for API Calls Source: https://github.com/google/oauth2l/blob/master/README.md Use the `header` command to get an `Authorization: Bearer` header. This is useful for integrating with tools like `curl`. ```bash $ oauth2l header --scope cloud-platform Authorization: Bearer ya29.zyxwvutsrqpnmolkjihgfedcba ``` ```bash $ curl -H "$(oauth2l header --scope pubsub)" https://pubsub.googleapis.com/v1/projects/my-project-id/topics ``` ```bash $ curl -H "$(oauth2l header --email user@example.com --credentials service_account_credentials.json --scope https://www.googleapis.com/auth/gmail.labels)" https://gmail.googleapis.com/gmail/v1/users/me/labels ``` -------------------------------- ### Get SSO token as Authorization header Source: https://context7.com/google/oauth2l/llms.txt Generates an Authorization header containing an SSO token. This is useful for making authenticated API requests directly. ```bash # SSO token as Authorization header $ oauth2l header \ --type sso \ --email me@google.com \ --scope cloud-platform Authorization: Bearer ya29.zyxwvutsrqpnmolkjihgfedcba ``` -------------------------------- ### Launch OAuth2l Playground Web App Source: https://github.com/google/oauth2l/blob/master/README.md The `web` command deploys and launches the OAuth2l Playground web application locally. Requires Docker and docker-compose. This feature is experimental. ```bash $ oauth2l web ``` -------------------------------- ### Fetch Token with Service Account and User Email for Delegation Source: https://github.com/google/oauth2l/blob/master/README.md Uses service account credentials to fetch a token, specifying a user email for domain-wide delegation. Requires the scope parameter. ```bash $ oauth2l fetch --credentials ~/service_account.json --scope cloud-platform --email user@google.com ``` -------------------------------- ### Fetch OAuth Access Token (2-legged) Source: https://github.com/google/oauth2l/blob/master/README.md Use this command to fetch an OAuth access token using the 2-legged OAuth flow when a service account key is provided. ```bash $ oauth2l fetch --type oauth --credentials ~/client_credentials.json --scope cloud-platform ``` -------------------------------- ### Run oauth2l Docker Image Source: https://github.com/google/oauth2l/blob/master/README.md Execute the oauth2l Docker image directly to fetch headers. This is useful for quick testing or integration. ```bash $ docker run -it gcr.io/oauth2l/oauth2l header cloud-platform ``` -------------------------------- ### Manage OAuth2l Token Cache Source: https://context7.com/google/oauth2l/llms.txt Demonstrates how to fetch tokens and manage the persistent local token cache. The cache is automatically used unless disabled or cleared. ```bash # Default cache location (~/.oauth2l) — automatic, no flags needed $ oauth2l fetch --scope cloud-platform ya29.zyxwvutsrqpnmolkjihgfedcba # fetched fresh, cached $ oauth2l fetch --scope cloud-platform ya29.zyxwvutsrqpnmolkjihgfedcba # served from cache ``` ```bash # Use a project-specific cache file $ oauth2l fetch \ --credentials ~/service_account.json \ --scope cloud-platform \ --cache ~/.oauth2l-my-project ``` ```bash # Disable caching for a single invocation $ oauth2l fetch --scope cloud-platform --cache "" ``` ```bash # Clear the entire cache (all stored tokens) $ oauth2l reset ``` ```bash # Clear a specific custom cache $ oauth2l reset --cache ~/.oauth2l-my-project ``` ```bash # Inspect the raw cache file (JSON format) $ cat ~/.oauth2l | python3 -m json.tool ``` -------------------------------- ### Fetch Token with Service Account (2LO) Source: https://context7.com/google/oauth2l/llms.txt Performs 2-legged OAuth (2LO) using a service account key JSON. This method does not require user interaction. ```bash # 2LO: service account key (no user interaction) $ oauth2l fetch \ --type oauth \ --credentials ~/service_account.json \ --scope cloud-platform ya29.zyxwvutsrqpnmolkjihgfedcba ``` -------------------------------- ### Fetch SSO Token with Custom SSO CLI, Email, and Scope Source: https://github.com/google/oauth2l/blob/master/README.md Fetches an SSO token using a custom SSO CLI, specifying the path to the CLI, the user's email, and the required scope. ```bash $ oauth2l fetch --type sso --ssocli /usr/bin/sso --email me@google.com --scope cloud-platform ``` -------------------------------- ### Fetch SSO token with custom CLI Source: https://context7.com/google/oauth2l/llms.txt Fetches an OAuth access token using a specified custom SSO CLI binary. This allows flexibility in choosing the SSO tool. ```bash # SSO with custom CLI binary $ oauth2l fetch \ --type sso \ --ssocli /usr/bin/my-sso-tool \ --email me@example.com \ --scope cloud-platform,pubsub ``` -------------------------------- ### Use Docker Image Directly or Inject into Container Source: https://context7.com/google/oauth2l/llms.txt Demonstrates using the oauth2l Docker image directly or injecting it into an existing container image via a Dockerfile. ```bash # Use the Docker image directly without installing $ docker run -it gcr.io/oauth2l/oauth2l header cloud-platform ``` ```dockerfile # Inject oauth2l into an existing container image # Dockerfile: FROM my-awesome-container COPY --from gcr.io/oauth2l/oauth2l /bin/oauth2l /bin/oauth2l ``` -------------------------------- ### Fetch Token with Custom Cache Path Source: https://github.com/google/oauth2l/blob/master/README.md Fetches a token and specifies a custom path for the token cache file. An empty string disables caching. ```bash $ oauth2l fetch --cache ~/different_path/.oauth2l --scope cloud-platform ``` -------------------------------- ### Build HTTP Authorization Header (Go) Source: https://context7.com/google/oauth2l/llms.txt Constructs a standard HTTP `Authorization` header string from a token type and access token. This utility is used internally by the `header` and `curl` commands. ```go package main import ( "context" "fmt" "log" "net/http" "os" "github.com/google/oauth2l/util" ) func main() { ctx := context.Background() credBytes, _ := os.ReadFile("service_account.json") settings := &util.Settings{ AuthType: util.AuthTypeOAuth, CredentialsJSON: string(credBytes), Scope: "https://www.googleapis.com/auth/pubsub", } token, err := util.FetchToken(ctx, settings) if err != nil { log.Fatal(err) } // Build Authorization header header := util.BuildHeader(token.TokenType, token.AccessToken) fmt.Println(header) // Output: Authorization: Bearer ya29.zyxwvutsrqpnmolkjihgfedcba // Use in an HTTP request req, _ := http.NewRequest("GET", "https://pubsub.googleapis.com/v1/projects/my-project/topics", nil) req.Header.Set("Authorization", token.TokenType+" "+token.AccessToken) client := http.DefaultClient resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() fmt.Println("Response status:", resp.Status) } ``` -------------------------------- ### Set Fetch Token Output Format Source: https://github.com/google/oauth2l/blob/master/README.md Control the output format of tokens fetched with the `fetch` command using `--output_format`. Available options include `bare`, `header`, `json`, `json_compact`, `pretty`, and `refresh_token`. The default is `bare`. ```bash $ oauth2l fetch --output_format pretty --scope cloud-platform ``` -------------------------------- ### Fetch SSO token with default CLI Source: https://context7.com/google/oauth2l/llms.txt Fetches an OAuth access token by invoking an external Single Sign-On (SSO) CLI tool. Uses the default SSO CLI path, typically in a Google corporate environment. ```bash # SSO with default CLI (Google corporate environment) $ oauth2l fetch \ --type sso \ --email me@google.com \ --scope cloud-platform ya29.zyxwvutsrqpnmolkjihgfedcba ``` -------------------------------- ### Fetch OAuth2 Tokens using Go API Source: https://context7.com/google/oauth2l/llms.txt Demonstrates fetching OAuth2 tokens using the `util.FetchToken` function in Go. Supports OAuth 2.0 flows, JWT self-signed tokens, and Application Default Credentials. ```go package main import ( "context" "fmt" "log" "os" "github.com/google/oauth2l/util" ) func main() { ctx := context.Background() // Read service account key credBytes, err := os.ReadFile("service_account.json") if err != nil { log.Fatal(err) } // Fetch OAuth token (2LO flow for service account) settings := &util.Settings{ AuthType: util.AuthTypeOAuth, CredentialsJSON: string(credBytes), Scope: "https://www.googleapis.com/auth/cloud-platform", } token, err := util.FetchToken(ctx, settings) if err != nil { log.Fatalf("FetchToken error: %v", err) } fmt.Println("Access Token:", token.AccessToken) fmt.Println("Token Type:", token.TokenType) fmt.Println("Expiry:", token.Expiry) // Fetch JWT token jwtSettings := &util.Settings{ AuthType: util.AuthTypeJWT, CredentialsJSON: string(credBytes), Audience: "https://pubsub.googleapis.com/", } jwtToken, err := util.FetchToken(ctx, jwtSettings) if err != nil { log.Fatalf("JWT FetchToken error: %v", err) } fmt.Println("JWT Token:", jwtToken.AccessToken) // Application Default Credentials (no settings) adcToken, err := util.FetchToken(ctx, nil) if err != nil { log.Fatalf("ADC FetchToken error: %v", err) } fmt.Println("ADC Token:", adcToken.AccessToken) } ``` -------------------------------- ### Fetch OAuth2 Token with Scopes Source: https://github.com/google/oauth2l/blob/master/README.md Use the 'fetch' command to retrieve an access token for specified OAuth scopes. The token is printed directly to standard output. ```bash $ oauth2l fetch --scope userinfo.email,cloud-platform ya29.zyxwvutsrqpnmolkjihgfedcba ``` -------------------------------- ### Fetch OAuth Token with Custom SSO CLI Source: https://github.com/google/oauth2l/blob/master/README.md Fetches an OAuth access token using a custom SSO CLI. Specify the path to the SSO CLI executable. Requires an email and scope. ```bash $ oauth2l header --type sso --ssocli /usr/bin/sso --email me@google.com --scope cloud-platform ``` -------------------------------- ### Specify Credentials File for Fetching Tokens Source: https://github.com/google/oauth2l/blob/master/README.md The `--credentials` option specifies an OAuth credential file (client ID or Service Account key). If not provided, it defaults to the `GOOGLE_APPLICATION_CREDENTIALS` environment variable. ```bash $ oauth2l fetch --credentials ~/service_account.json --scope cloud-platform ``` ```bash $ export GOOGLE_APPLICATION_CREDENTIALS="~/service_account.json" $ oauth2l fetch --scope cloud-platform ``` -------------------------------- ### Make Authenticated Curl Requests Source: https://github.com/google/oauth2l/blob/master/README.md The `curl` command is a shortcut to fetch an access token and use it with `curl`. Additional flags after `--` are passed directly to `curl`. ```bash $ oauth2l curl --scope cloud-platform,pubsub --url https://pubsub.googleapis.com/v1/projects/my-project-id/topics -- -i ``` ```bash $ oauth2l curl --email user@example.com --credentials service_account_credentials.json --scope https://www.googleapis.com/auth/gmail.labels --url https://gmail.googleapis.com/gmail/v1/users/me/labels ``` -------------------------------- ### Fetch OAuth Token with Default SSO CLI Source: https://github.com/google/oauth2l/blob/master/README.md Fetches an OAuth access token using the default SSO CLI, which is configured for Google's corporate SSO. Requires an email and scope. ```bash $ oauth2l header --type sso --email me@google.com --scope cloud-platform ``` -------------------------------- ### Inspect Token Information Source: https://github.com/google/oauth2l/blob/master/README.md The `info` command displays details about a token, including its expiration time and scopes. It may also show the authenticated user's email if specific scopes are present. ```bash $ oauth2l info --token $(oauth2l fetch --scope pubsub) { "expires_in": 3599, "scope": "https://www.googleapis.com/auth/pubsub", "email": "user@gmail.com" ... } ``` -------------------------------- ### Fetch JWT Token with Scope Source: https://github.com/google/oauth2l/blob/master/README.md Generates a JWT token signed by a service account private key. Requires either --audience or --scope. Use --scope for broader access. ```bash $ oauth2l fetch --type jwt --credentials ~/service_account.json --scope cloud-platform ``` -------------------------------- ### Generate Service Account Access Token (Go) Source: https://context7.com/google/oauth2l/llms.txt Exchanges a user access token for a Service Account access token using the IAM Credentials API. The caller's token requires `cloud-platform` or `iam` scope, and the service account can be specified by ID or email. ```go package main import ( "context" "fmt" "log" "os" "github.com/google/oauth2l/util" ) func main() { ctx := context.Background() // First fetch the caller's (user) access token credBytes, _ := os.ReadFile("client_credentials.json") userSettings := &util.Settings{ AuthType: util.AuthTypeOAuth, CredentialsJSON: string(credBytes), Scope: "https://www.googleapis.com/auth/cloud-platform", } userToken, err := util.FetchToken(ctx, userSettings) if err != nil { log.Fatalf("Failed to fetch user token: %v", err) } // Exchange user token for service account token scope := "https://www.googleapis.com/auth/cloud-platform" saToken, err := util.GenerateServiceAccountAccessToken( userToken.AccessToken, "target-sa@my-project.iam.gserviceaccount.com", scope, ) if err != nil { log.Fatalf("Impersonation failed: %v", err) } fmt.Println("SA Access Token:", saToken.AccessToken) fmt.Println("Expires at:", saToken.Expiry) // Use the impersonated token for an API call header := util.BuildHeader(saToken.TokenType, saToken.AccessToken) fmt.Println("HTTP Header:", header) // Output: HTTP Header: Authorization: Bearer ya29.impersonated-token } ``` -------------------------------- ### BuildHeader (Go API) Source: https://context7.com/google/oauth2l/llms.txt `BuildHeader` constructs a standard HTTP `Authorization` header string from a token type and access token value. Used internally by the `header` and `curl` commands and available as a utility function. ```APIDOC ## BuildHeader (Go API) `BuildHeader` constructs a standard HTTP `Authorization` header string from a token type and access token value. Used internally by the `header` and `curl` commands and available as a utility function. ### Usage ```go package main import ( "context" "fmt" "log" "net/http" "os" "github.com/google/oauth2l/util" ) func main() { ctx := context.Background() credBytes, _ := os.ReadFile("service_account.json") settings := &util.Settings{ AuthType: util.AuthTypeOAuth, CredentialsJSON: string(credBytes), Scope: "https://www.googleapis.com/auth/pubsub", } token, err := util.FetchToken(ctx, settings) if err != nil { log.Fatal(err) } // Build Authorization header header := util.BuildHeader(token.TokenType, token.AccessToken) fmt.Println(header) // Output: Authorization: Bearer ya29.zyxwvutsrqpnmolkjihgfedcba // Use in an HTTP request req, _ := http.NewRequest("GET", "https://pubsub.googleapis.com/v1/projects/my-project/topics", nil) req.Header.Set("Authorization", token.TokenType+" "+token.AccessToken) client := http.DefaultClient resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() fmt.Println("Response status:", resp.Status) } ``` ``` -------------------------------- ### Store Token in Variable for Multiple API Calls Source: https://context7.com/google/oauth2l/llms.txt Fetch a token and store it in a variable for subsequent API calls. Ensure the credentials and scope are correctly set. ```bash TOKEN=$(oauth2l fetch --credentials "$CREDENTIALS" --scope cloud-platform) curl -H "Authorization: Bearer $TOKEN" \ "https://cloudresourcemanager.googleapis.com/v1/projects/${PROJECT_ID}" curl -H "Authorization: Bearer $TOKEN" \ "https://pubsub.googleapis.com/v1/projects/${PROJECT_ID}/topics" ``` -------------------------------- ### Format Token as Authorization Header Source: https://context7.com/google/oauth2l/llms.txt Fetches an access token and formats it as an HTTP `Authorization: Bearer` header. Useful for direct integration with tools like `curl`. ```bash # Generate Authorization header $ oauth2l header --scope cloud-platform Authorization: Bearer ya29.zyxwvutsrqpnmolkjihgfedcba ``` ```bash # Use directly with curl to call a Google API $ curl -H "$(oauth2l header --scope cloud-platform)" \ https://cloudresourcemanager.googleapis.com/v1/projects ``` ```bash # List Pub/Sub topics $ curl -H "$(oauth2l header --scope pubsub)" \ https://pubsub.googleapis.com/v1/projects/my-project-id/topics ``` ```bash # Domain-wide delegation: list Gmail labels for a specific user $ curl -H "$(oauth2l header \ --email user@example.com \ --credentials service_account.json \ --scope https://www.googleapis.com/auth/gmail.labels)" \ https://gmail.googleapis.com/gmail/v1/users/me/labels ``` ```bash # Using SSO authentication $ oauth2l header --type sso --email me@google.com --scope cloud-platform Authorization: Bearer ya29.zyxwvutsrqpnmolkjihgfedcba ``` -------------------------------- ### Fetch STS Token with Audience and Quota Project Source: https://github.com/google/oauth2l/blob/master/README.md Exchanges a fetched access token with an STS token. This command includes 'audience' and 'quota_project' claims. Compatible with oauth and sso types, but not jwt. ```bash $ oauth2l fetch --sts --audience https://pubsub.googleapis.com/ --quota_project quotaprojectid ``` -------------------------------- ### Stop OAuth2l Playground Web App Source: https://github.com/google/oauth2l/blob/master/README.md Use the `--stop` flag with the `web` command to halt the OAuth2l Playground web application. ```bash $ oauth2l web --stop ``` -------------------------------- ### Fetch Token with Comma-Delimited Scopes Source: https://github.com/google/oauth2l/blob/master/README.md Fetches an OAuth access token with multiple scopes specified as a comma-delimited list. This is required for oauth and sso authentication types. ```bash $ oauth2l fetch --scope cloud-platform,pubsub ``` -------------------------------- ### GenerateServiceAccountAccessToken (Go API) Source: https://context7.com/google/oauth2l/llms.txt `GenerateServiceAccountAccessToken` calls the IAM Credentials API to exchange a user access token for a Service Account access token. The caller's token must have `cloud-platform` or `iam` scope. The service account parameter accepts either a numeric ID or an email address. ```APIDOC ## GenerateServiceAccountAccessToken (Go API) `GenerateServiceAccountAccessToken` calls the IAM Credentials API to exchange a user access token for a Service Account access token. The caller's token must have `cloud-platform` or `iam` scope. The service account parameter accepts either a numeric ID or an email address. ### Usage ```go package main import ( "context" "fmt" "log" "os" "github.com/google/oauth2l/util" ) func main() { ctx := context.Background() // First fetch the caller's (user) access token credBytes, _ := os.ReadFile("client_credentials.json") userSettings := &util.Settings{ AuthType: util.AuthTypeOAuth, CredentialsJSON: string(credBytes), Scope: "https://www.googleapis.com/auth/cloud-platform", } userToken, err := util.FetchToken(ctx, userSettings) if err != nil { log.Fatalf("Failed to fetch user token: %v", err) } // Exchange user token for service account token scope := "https://www.googleapis.com/auth/cloud-platform" saToken, err := util.GenerateServiceAccountAccessToken( userToken.AccessToken, "target-sa@my-project.iam.gserviceaccount.com", scope, ) if err != nil { log.Fatalf("Impersonation failed: %v", err) } fmt.Println("SA Access Token:", saToken.AccessToken) fmt.Println("Expires at:", saToken.Expiry) // Use the impersonated token for an API call header := util.BuildHeader(saToken.TokenType, saToken.AccessToken) fmt.Println("HTTP Header:", header) // Output: HTTP Header: Authorization: Bearer ya29.impersonated-token } ``` ``` -------------------------------- ### Execute curl with Injected OAuth Token Source: https://context7.com/google/oauth2l/llms.txt Fetches an access token and executes a curl request with the token in the Authorization header. Pass extra curl flags after `--`. Equivalent to combining `header` output with a manual `curl` invocation. ```bash # Basic API request with oauth token injected automatically $ oauth2l curl \ --scope cloud-platform,pubsub \ --url https://pubsub.googleapis.com/v1/projects/my-project-id/topics ``` ```bash # Pass extra curl flags (e.g., -i to include response headers) $ oauth2l curl \ --scope cloud-platform \ --url https://pubsub.googleapis.com/v1/projects/my-project-id/topics \ -- -i ``` ```bash # POST request with JSON body $ oauth2l curl \ --scope cloud-platform \ --url https://pubsub.googleapis.com/v1/projects/my-project-id/topics/my-topic \ -- -X POST -H "Content-Type: application/json" \ -d '{"labels":{"env":"prod"}}' ``` ```bash # Domain-wide delegation with service account $ oauth2l curl \ --email user@example.com \ --credentials service_account.json \ --scope https://www.googleapis.com/auth/gmail.labels \ --url https://gmail.googleapis.com/gmail/v1/users/me/labels ``` ```bash # Use a custom curl binary $ oauth2l curl \ --curlcli /usr/local/bin/curl \ --scope cloud-platform \ --url https://pubsub.googleapis.com/v1/projects/my-project-id/topics ``` -------------------------------- ### Use oauth2l curl for Full Pipeline Integration Source: https://context7.com/google/oauth2l/llms.txt Integrate oauth2l directly with curl for streamlined API calls within pipelines. The `-- -s` passes arguments to the underlying curl command, and the output is piped to `json.tool` for pretty-printing. ```bash oauth2l curl \ --credentials "$CREDENTIALS" \ --scope cloud-platform \ --url "https://pubsub.googleapis.com/v1/projects/${PROJECT_ID}/topics" \ -- -s | python3 -m json.tool ``` -------------------------------- ### Fetch Google OAuth 2.0 Access Token Source: https://context7.com/google/oauth2l/llms.txt Fetches and prints an OAuth 2.0 access token for specified scopes. Supports various credential sources and output formats. Tokens are cached by default. ```bash # Bare token using Application Default Credentials (ADC) $ oauth2l fetch --scope cloud-platform ya29.zyxwvutsrqpnmolkjihgfedcba ``` ```bash # From an explicit service account key file, multiple scopes $ oauth2l fetch --credentials ~/service_account.json --scope cloud-platform,pubsub ya29.zyxwvutsrqpnmolkjihgfedcba ``` ```bash # Using GOOGLE_APPLICATION_CREDENTIALS environment variable $ export GOOGLE_APPLICATION_CREDENTIALS="~/service_account.json" $ oauth2l fetch --scope cloud-platform ya29.zyxwvutsrqpnmolkjihgfedcba ``` ```bash # JSON output format $ oauth2l fetch --scope cloud-platform --output_format json { "access_token": "ya29.zyxwvutsrqpnmolkjihgfedcba", "token_type": "Bearer", "expiry": "2024-01-15T10:30:00Z" } ``` ```bash # Pretty output format showing credential type $ oauth2l fetch --scope cloud-platform --output_format pretty Fetched credentials of type: service_account Access Token: ya29.zyxwvutsrqpnmolkjihgfedcba ``` ```bash # Compact JSON output $ oauth2l fetch --scope cloud-platform --output_format json_compact {"access_token":"ya29.zyxwvutsrqpnmolkjihgfedcba","token_type":"Bearer","expiry":"2024-01-15T10:30:00Z"} ``` ```bash # Fetch and print as Authorization header value $ oauth2l fetch --scope cloud-platform --output_format header Authorization: Bearer ya29.zyxwvutsrqpnmolkjihgfedcba ``` ```bash # Output refresh token (only valid for OAuth Client ID / authorized_user credentials) $ oauth2l fetch --credentials ~/client_credentials.json --scope cloud-platform --output_format refresh_token {"client_id":"...","client_secret":"...","refresh_token":"1//...","token_uri":"https://oauth2.googleapis.com/token","type":"authorized_user"} ``` ```bash # Custom cache location $ oauth2l fetch --scope cloud-platform --cache /tmp/my_token_cache ``` ```bash # Disable caching entirely $ oauth2l fetch --scope cloud-platform --cache "" ``` -------------------------------- ### Fetch SSO Token with Email and Scope Source: https://github.com/google/oauth2l/blob/master/README.md Fetches an SSO token, requiring the associated email and scope. This is a common use case for the sso authentication type. ```bash $ oauth2l fetch --type sso --email me@google.com --scope cloud-platform ``` -------------------------------- ### Inject oauth2l into Docker Container Source: https://github.com/google/oauth2l/blob/master/README.md Copy the oauth2l binary from its Docker image into an existing container. Ensure the binary is placed in a directory included in the container's PATH. ```dockerfile FROM my-awesome-container COPY --from gcr.io/oauth2l/oauth2l /bin/oauth2l /bin/oauth2l ``` -------------------------------- ### Use impersonated token in curl request Source: https://context7.com/google/oauth2l/llms.txt Demonstrates how to use an impersonated service account token with `curl` for making authenticated API requests. Requires credentials, scope, and the target service account. ```bash # Use impersonated token in a curl request $ oauth2l curl \ --credentials ~/client_credentials.json \ --scope cloud-platform \ --impersonate-service-account target-sa@my-project.iam.gserviceaccount.com \ --url https://pubsub.googleapis.com/v1/projects/my-project-id/topics ``` -------------------------------- ### Fetch JWT Token with Audience Source: https://github.com/google/oauth2l/blob/master/README.md Generates a JWT token signed by a service account private key. Requires either --audience or --scope. Use --audience for specific service endpoints. ```bash $ oauth2l fetch --type jwt --credentials ~/service_account.json --audience https://pubsub.googleapis.com/ ``` -------------------------------- ### Fetch token delegated to a specific user Source: https://context7.com/google/oauth2l/llms.txt Fetches a token using a service account with domain-wide delegation enabled, allowing it to act on behalf of a specified user. Requires service account credentials, scope, and the user's email. ```bash # Fetch token delegated to a specific user $ oauth2l fetch \ --credentials ~/service_account.json \ --scope https://www.googleapis.com/auth/gmail.readonly \ --email user@yourdomain.com ya29.zyxwvutsrqpnmolkjihgfedcba ``` -------------------------------- ### Fetch STS Token with Quota Project Source: https://github.com/google/oauth2l/blob/master/README.md Exchanges a fetched access token with an STS token, specifying the quota project for billing override. This is compatible with oauth and sso authentication types. ```bash $ oauth2l fetch --sts --quota_project quotaprojectid ``` -------------------------------- ### Validate Token Before Use Source: https://context7.com/google/oauth2l/llms.txt Check if a stored token is still valid before using it. If expired, reset and fetch a new token. Redirects output to /dev/null to suppress test command output. ```bash if ! oauth2l test --token "$TOKEN" > /dev/null 2>&1; then echo "Token expired, fetching new one..." oauth2l reset TOKEN=$(oauth2l fetch --credentials "$CREDENTIALS" --scope cloud-platform) fi ``` -------------------------------- ### Fetch Token and Impersonate Service Account Source: https://github.com/google/oauth2l/blob/master/README.md Exchanges a fetched User access token with a Service Account access token using Google's IAM Service. Requires credentials, scope (including 'cloud-platform' or 'iam'), and the service account ID or email. ```bash $ oauth2l fetch --credentials ~/client_credentials.json --scope cloud-platform,pubsub --impersonate-service-account 113258942105700140798 ``` -------------------------------- ### Fetch Token and Refresh Expired Token Source: https://github.com/google/oauth2l/blob/master/README.md Fetches a token and attempts to refresh an expired access token from the cache using a refresh token instead of re-authorizing. Requires credentials and scope. ```bash $ oauth2l fetch --credentials ~/client_credentials.json --scope cloud-platform --refresh ``` -------------------------------- ### Generate JWT token with scope Source: https://context7.com/google/oauth2l/llms.txt Generates a self-signed JWT token for Google API access. Requires a service account JSON file and a scope. ```bash # JWT with scope (for Google API access) $ oauth2l fetch \ --type jwt \ --credentials ~/service_account.json \ --scope cloud-platform eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9... ``` -------------------------------- ### STS token exchange with audience and quota project Source: https://context7.com/google/oauth2l/llms.txt Performs an STS token exchange including both audience and quota project claims. This provides fine-grained control over the STS token's usage and billing. ```bash # STS with both audience and quota_project $ oauth2l fetch \ --credentials ~/service_account.json \ --scope cloud-platform \ --sts \ --audience https://pubsub.googleapis.com/ \ --quota_project my-quota-project ``` -------------------------------- ### Impersonate service account by email Source: https://context7.com/google/oauth2l/llms.txt Exchanges a user access token for a service account access token using the IAM Credentials API. Requires service account email and appropriate scopes. ```bash # Impersonate by service account email $ oauth2l fetch \ --credentials ~/client_credentials.json \ --scope cloud-platform \ --impersonate-service-account target-sa@my-project.iam.gserviceaccount.com ``` -------------------------------- ### StsExchange (Go API) Source: https://context7.com/google/oauth2l/llms.txt `StsExchange` exchanges an existing OAuth access token for an STS token via Google's Secure Token Service. The `EncodeClaims` helper encodes optional `audience` and `quota_project` claims as a base64 JSON string passed in the `X-Goog-Auth-Claims` header. ```APIDOC ## StsExchange (Go API) `StsExchange` exchanges an existing OAuth access token for an STS token via Google's Secure Token Service. The `EncodeClaims` helper encodes optional `audience` and `quota_project` claims as a base64 JSON string passed in the `X-Goog-Auth-Claims` header. ### Usage ```go package main import ( "fmt" "log" "github.com/google/oauth2l/util" ) func main() { // First fetch a base OAuth token baseToken := "ya29.base-oauth-token" // Encode STS claims settings := &util.Settings{ Audience: "https://pubsub.googleapis.com/", QuotaProject: "my-quota-project", } encodedClaims := util.EncodeClaims(settings) // encodedClaims is a base64-encoded JSON: {"audience":"...","user_project":"..."} // Exchange for STS token stsToken, err := util.StsExchange(baseToken, encodedClaims) if err != nil { log.Fatalf("STS exchange failed: %v", err) } fmt.Println("STS Access Token:", stsToken.AccessToken) fmt.Println("Token Type:", stsToken.TokenType) // Exchange with no claims (empty audience/quota) emptyClaims := util.EncodeClaims(&util.Settings{}) plainStsToken, err := util.StsExchange(baseToken, emptyClaims) if err != nil { log.Fatalf("STS exchange failed: %v", err) } fmt.Println("Plain STS Token:", plainStsToken.AccessToken) } ``` ``` -------------------------------- ### Set Consent Page Interaction Timeout Source: https://github.com/google/oauth2l/blob/master/README.md Configure the time to wait for user interaction on the consent page in 3LO loopback flows using `--consentPageInteractionTimeout`. After the timeout, the `redirect_uri` localhost will become unavailable. The default is 2 units, which can be changed with `--consentPageInteractionTimeoutUnits`. -------------------------------- ### Access Gmail API as delegated user via header Source: https://context7.com/google/oauth2l/llms.txt Constructs an Authorization header for accessing the Gmail API as a delegated user. This uses domain-wide delegation with service account credentials. ```bash # Access Gmail API as delegated user $ curl -H "$(oauth2l header \ --credentials ~/service_account.json \ --email user@yourdomain.com \ --scope https://www.googleapis.com/auth/gmail.labels)" \ https://gmail.googleapis.com/gmail/v1/users/me/labels ``` -------------------------------- ### Fetch JWT Token with Audience Only Source: https://github.com/google/oauth2l/blob/master/README.md Fetches a JWT token, specifying only the audience. This is required for the jwt authentication type. ```bash $ oauth2l fetch --type jwt --audience https://pubsub.googleapis.com/ ``` -------------------------------- ### Use JWT as header for API call Source: https://context7.com/google/oauth2l/llms.txt Constructs an Authorization header using a JWT token for direct API calls. This is useful for integrating with services that expect JWT authentication. ```bash # Use JWT as header for a direct API call $ curl -H "$(oauth2l header \ --type jwt \ --credentials ~/service_account.json \ --audience https://pubsub.googleapis.com/)" \ https://pubsub.googleapis.com/v1/projects/my-project-id/topics ``` -------------------------------- ### Generate JWT token with audience Source: https://context7.com/google/oauth2l/llms.txt Generates a self-signed JWT token for direct service-to-service calls. Requires a service account JSON file and an audience URL. ```bash $ oauth2l fetch \ --type jwt \ --credentials ~/service_account.json \ --audience https://pubsub.googleapis.com/ eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9... ``` -------------------------------- ### STS Token for Quota Project Override Source: https://context7.com/google/oauth2l/llms.txt Utilize Security Token Service (STS) to obtain a token with a specified quota project override. This is useful for billing or quota management in shared environments. ```bash oauth2l curl \ --credentials "$CREDENTIALS" \ --scope cloud-platform \ --sts \ --quota_project "billing-override-project" \ --url "https://bigquery.googleapis.com/bigquery/v2/projects/${PROJECT_ID}/datasets" ``` -------------------------------- ### Test Token Validity Source: https://github.com/google/oauth2l/blob/master/README.md Use the `test` command to check if a token is valid. It sets the exit code to 0 for valid tokens and 1 for invalid tokens, suitable for shell scripting. ```bash $ oauth2l test --token ya29.zyxwvutsrqpnmolkjihgfedcba 0 $ echo $? 0 $ oauth2l test --token ya29.justkiddingmadethisoneup 1 $ echo $? ``` -------------------------------- ### Exchange OAuth Token for STS Token (Go) Source: https://context7.com/google/oauth2l/llms.txt Exchanges an existing OAuth access token for an STS token. The `EncodeClaims` helper can be used to add optional audience and quota project claims. ```go package main import ( "fmt" "log" "github.com/google/oauth2l/util" ) func main() { // First fetch a base OAuth token baseToken := "ya29.base-oauth-token" // Encode STS claims settings := &util.Settings{ Audience: "https://pubsub.googleapis.com/", QuotaProject: "my-quota-project", } encodedClaims := util.EncodeClaims(settings) // encodedClaims is a base64-encoded JSON: {"audience":"...","user_project":"..."} // Exchange for STS token stsToken, err := util.StsExchange(baseToken, encodedClaims) if err != nil { log.Fatalf("STS exchange failed: %v", err) } fmt.Println("STS Access Token:", stsToken.AccessToken) fmt.Println("Token Type:", stsToken.TokenType) // Exchange with no claims (empty audience/quota) emptyClaims := util.EncodeClaims(&util.Settings{}) plainStsToken, err := util.StsExchange(baseToken, emptyClaims) if err != nil { log.Fatalf("STS exchange failed: %v", err) } fmt.Println("Plain STS Token:", plainStsToken.AccessToken) } ``` -------------------------------- ### STS token exchange with quota project override Source: https://context7.com/google/oauth2l/llms.txt Exchanges an OAuth access token for an STS token, specifying a quota project override. This allows for billing or quota management. ```bash # STS exchange with quota project override $ oauth2l fetch \ --scope cloud-platform \ --sts \ --quota_project my-billing-project-id ``` -------------------------------- ### Inspect OAuth2 Token Metadata Source: https://context7.com/google/oauth2l/llms.txt Queries Google's token introspection endpoint to print metadata about a token. Includes scopes, expiration time, and optionally the authenticated email if the `userinfo.email` scope was granted. ```bash # Inspect a token passed inline $ oauth2l info --token ya29.zyxwvutsrqpnmolkjihgfedcba { "azp": "123456789.apps.googleusercontent.com", "aud": "123456789.apps.googleusercontent.com", "scope": "https://www.googleapis.com/auth/pubsub", "exp": "1705312800", "expires_in": "3599", "email": "user@example.com", "email_verified": "true", "access_type": "online" } ``` ```bash # Pipe a freshly fetched token into info $ oauth2l info --token $(oauth2l fetch --scope pubsub) { "scope": "https://www.googleapis.com/auth/pubsub", "expires_in": "3599", "email": "service-account@my-project.iam.gserviceaccount.com" } ``` -------------------------------- ### Domain-wide delegation via oauth2l curl Source: https://context7.com/google/oauth2l/llms.txt Makes an API call using `oauth2l curl` with domain-wide delegation. This allows the service account to act as the specified user for the requested API endpoint. ```bash # Domain-wide delegation via oauth2l curl $ oauth2l curl \ --credentials ~/service_account.json \ --email user@yourdomain.com \ --scope https://www.googleapis.com/auth/calendar.readonly \ --url "https://www.googleapis.com/calendar/v3/calendars/primary/events" ``` -------------------------------- ### Impersonate service account by numeric ID Source: https://context7.com/google/oauth2l/llms.txt Exchanges a user access token for a service account access token using the IAM Credentials API, specifying the service account by its numeric ID. Requires appropriate scopes. ```bash # Impersonate by service account numeric ID $ oauth2l fetch \ --credentials ~/client_credentials.json \ --scope cloud-platform,pubsub \ --impersonate-service-account 113258942105700140798 ``` -------------------------------- ### JWT for Service-to-Service Authentication Source: https://context7.com/google/oauth2l/llms.txt Generate a JWT token for service-to-service authentication. This is typically used when one service needs to authenticate to another internal service. ```bash JWT_TOKEN=$(oauth2l fetch \ --type jwt \ --credentials "$CREDENTIALS" \ --audience "https://my-internal-service.example.com/") curl -H "Authorization: Bearer $JWT_TOKEN" \ "https://my-internal-service.example.com/api/v1/data" ``` -------------------------------- ### Reset Cached Tokens Source: https://github.com/google/oauth2l/blob/master/README.md The `reset` command clears all locally cached OAuth2 tokens stored in `~/.oauth2l` by default. ```bash $ oauth2l reset ``` -------------------------------- ### Specify URL for Curl Command Source: https://github.com/google/oauth2l/blob/master/README.md The `--url` flag is required for the `curl` command to specify the target URL endpoint for the request. ```bash $ oauth2l curl --scope cloud-platform --url https://pubsub.googleapis.com/v1/projects/my-project-id/topics ``` -------------------------------- ### Disable Auto-Open Consent Page in 3LO Source: https://github.com/google/oauth2l/blob/master/README.md Use `--disableAutoOpenConsentPage` to prevent the automatic opening of the consent page in 3LO loopback flows. The user will receive a URL to manually interact with the consent page. This flag requires no arguments. ```bash $ oauth2l fetch --credentials ~/client_credentials.json --disableAutoOpenConsentPage --consentPageInteractionTimeout 60 --consentPageInteractionTimeoutUnits seconds --scope cloud-platform ```