Last active
November 15, 2021 18:37
-
-
Save salrashid123/052d7e1e192beb2f6ebf2dea488379ef to your computer and use it in GitHub Desktop.
GCP WorkloadIdentityFederation --> Cloud Run
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"io/ioutil" | |
"net/http" | |
"log" | |
"golang.org/x/oauth2" | |
"google.golang.org/api/impersonate" | |
"google.golang.org/api/option" | |
htransport "google.golang.org/api/transport/http" | |
) | |
var () | |
func main() { | |
ctx := context.Background() | |
// ************************************************* | |
aud := "https://myapp-6w42z6vi3q-uc.a.run.app" | |
url := "https://myapp-6w42z6vi3q-uc.a.run.app" | |
selfTarget := "[email protected]" | |
idTokenSource, err := impersonate.IDTokenSource(ctx, | |
impersonate.IDTokenConfig{ | |
TargetPrincipal: selfTarget, | |
Audience: aud, | |
IncludeEmail: true, | |
}, | |
) | |
if err != nil { | |
log.Fatalf("%v", err) | |
} | |
/// ***************************************** | |
// A | |
hclient := &http.Client{ | |
Transport: &oauth2.Transport{ | |
Source: idTokenSource, | |
}, | |
} | |
hresp, err := hclient.Get(url) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer hresp.Body.Close() | |
log.Println("Response status:", hresp.Status) | |
hbodyBytes, err := ioutil.ReadAll(hresp.Body) | |
if err != nil { | |
log.Fatal(err) | |
} | |
hbodyString := string(hbodyBytes) | |
log.Printf("%s", hbodyString) | |
/// ***************************************** | |
// B | |
// https://github.com/googleapis/google-api-go-client/blob/main/idtoken/idtoken.go#L46 | |
// gives idtoken: option.WithTokenSource not supported | |
// client, err := idtoken.NewClient(ctx, aud, option.WithTokenSource(idTokenSource)) | |
// if err != nil { | |
// log.Fatalf("%v", err) | |
// } | |
t, err := htransport.NewTransport(ctx, http.DefaultTransport, option.WithTokenSource(idTokenSource)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
client := &http.Client{Transport: t} | |
resp, err := client.Get(url) | |
if err != nil { | |
log.Fatalf("Error Creating HTTP Request: %v", err) | |
} | |
bodyBytes, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
log.Fatalf("Error Reading response body: %v", err) | |
} | |
bodyString := string(bodyBytes) | |
log.Printf("Authenticated Response: %v", bodyString) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment