Last active
October 4, 2017 08:55
-
-
Save kbhaines/3f22d3f25bd49b17fa511f00d79b8368 to your computer and use it in GitHub Desktop.
GoLang Oauth2 using Google Application Default Credentials
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" | |
| "fmt" | |
| "log" | |
| "net/http" | |
| "golang.org/x/oauth2/google" | |
| "google.golang.org/api/oauth2/v2" | |
| ) | |
| func appDefToken() string { | |
| ts, err := google.DefaultTokenSource(context.TODO(), oauth2.UserinfoEmailScope) | |
| if err != nil { | |
| log.Fatalf("token source: %v", err) | |
| } | |
| token, err := ts.Token() | |
| if err != nil { | |
| log.Fatalf("token: %v", err) | |
| } | |
| return token.AccessToken | |
| } | |
| func main() { | |
| oauthHttpClient := new(http.Client) | |
| oauth2Service, err := oauth2.New(oauthHttpClient) | |
| if err != nil { | |
| log.Fatalf("could not get service: %v", err) | |
| } | |
| token := appDefToken() | |
| info, err := oauth2Service.Tokeninfo().AccessToken(token).Do() | |
| if err != nil { | |
| log.Fatalf("Error: token error %v", err) | |
| } | |
| if info.Email != "" { | |
| fmt.Println(info.Email) | |
| } else { | |
| fmt.Println("No email for token: ", info) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment