← Back to list

Golang: Acquiring Google OAuth2 Tokens Behind a Proxy

We have leveraged the ‘google.golang.org/api/idtoken’ package to develop a REST API that interfaces with Google Cloud Platform services…

Paween Pongthong · 2025-01-10 10:47 · 0 claps · 0.9 min read
#golang #google-cloud-platform #idtoken #oauth2 #http-proxy
Open on Medium ↗
Wiki topics: RAG · RAG & Retrieval ☁️ · DevOps & Cloud

Golang: Acquiring Google OAuth2 Tokens Behind a Proxy

We have leveraged the ‘google.golang.org/api/idtoken’ package to develop a REST API that interfaces with Google Cloud Platform services. This implementation is designed to operate within a constrained intranet environment, where outbound traffic is routed through an HTTP proxy to facilitate authentication token acquisition.

import "google.golang.org/api/idtoken"

ctx := context.Background()
tokenSource, err := idtoken.NewTokenSource(ctx, audience, idtoken.WithCredentialsFile(credentialsFile))

To acquire tokens using this library function, it is necessary to establish an HTTP client configured with a proxy.

proxy, err := url.Parse(proxyURL)
if err != nil {
 return fmt.Errorf("invalid proxy URL: %v", err)
}

httpClient := &http.Client{
 Transport: &http.Transport{
  Proxy: http.ProxyURL(proxy),
 },
}

Inject the http client into the context.

ctx1 := context.Background()
ctx2 := context.WithValue(ctx1, oauth2.HTTPClient, httpClient)

Here is the full code.

import "google.golang.org/api/idtoken"

proxy, err := url.Parse(proxyURL)
if err != nil {
 return fmt.Errorf("invalid proxy URL: %v", err)
}

httpClient := &http.Client{
 Transport: &http.Transport{
  Proxy: http.ProxyURL(proxy),
 },
}

ctx1 := context.Background()
ctx2 := context.WithValue(ctx1, oauth2.HTTPClient, httpClient)
tokenSource, err := idtoken.NewTokenSource(ctx2, audience, idtoken.WithCredentialsFile(credentialsFile))

This code demonstrates how to authenticate with Google Cloud using the provided credentials and configure the HTTP client to work through an HTTP proxy.


메타데이터
post_id
dfc73ce56da2
slug
how-to-request-google-token-via-proxy-with-golang-dfc73ce56da2
url
https://medium.com/@paween-p/how-to-request-google-token-via-proxy-with-golang-dfc73ce56da2
canonical_url
https://medium.com/@paween-p/how-to-request-google-token-via-proxy-with-golang-dfc73ce56da2
author_url
https://medium.com/@paween-p
status
ok
fetched_at
2026-06-26 21:52:29