Skip to content

Instantly share code, notes, and snippets.

@salrashid123
Last active November 1, 2020 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salrashid123/fd3236d7405748120089d2c93f71faac to your computer and use it in GitHub Desktop.
Save salrashid123/fd3236d7405748120089d2c93f71faac to your computer and use it in GitHub Desktop.
Impersonated IdToken
package main
/*
>>>>>>> update 1/11/20: this does not work anymore since i migrated the identity token and impersonated tokento separte modules.
//
https://github.com/salrashid123/oauth2/blob/master/idtoken/idtoken.go#L130
*/
import (
"context"
"io/ioutil"
"log"
"net/http"
"time"
sal "github.com/salrashid123/oauth2/impersonate"
idsal "github.com/salrashid123/oauth2/idtoken"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
func main() {
ctx := context.Background()
data, err := ioutil.ReadFile("/path/to/svc.json")
if err != nil {
log.Fatal(err)
}
sacreds, err := google.CredentialsFromJSON(ctx, data, "https://www.googleapis.com/auth/cloud-platform")
sourceTok := sacreds.TokenSource
if err != nil {
log.Fatal(err)
}
targetPrincipal := "impersonated-account@project.iam.gserviceaccount.com"
lifetime := 30 * time.Second
delegates := []string{}
targetScopes := []string{"https://www.googleapis.com/auth/cloud-platform"}
impersonatedTokenSource, err := sal.ImpersonatedTokenSource(
&sal.ImpersonatedTokenConfig{
RootTokenSource: sourceTok,
TargetPrincipal: targetPrincipal,
Lifetime: lifetime,
Delegates: delegates,
TargetScopes: targetScopes,
},
)
impersonatedCreds := &google.Credentials{
TokenSource: impersonatedTokenSource,
}
targetAudience := "https://foo.bar"
idTokenSource, err := idsal.IdTokenSource(
&idsal.IdTokenConfig{
Credentials: impersonatedCreds,
Audiences: []string{targetAudience},
IAMExtension: idsal.IAMExtension{
IncludeEmail: true,
},
},
)
client := &http.Client{
Transport: &oauth2.Transport{
Source: idTokenSource,
},
}
url := "https://httpbin.org/get"
resp, err := client.Get(url)
if err != nil {
log.Fatal(err)
}
log.Printf("Response: %v", resp.Status)
responseData, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Printf(string(responseData))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment