Skip to content

Instantly share code, notes, and snippets.

@lsjostro
Created November 6, 2018 08:25
Show Gist options
  • Save lsjostro/2f26d72b21e2bb48aa012d39d249dc53 to your computer and use it in GitHub Desktop.
Save lsjostro/2f26d72b21e2bb48aa012d39d249dc53 to your computer and use it in GitHub Desktop.
google-auth
package main
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"golang.org/x/oauth2/google"
)
var (
scopes = []string{"https://www.googleapis.com/auth/cloud-platform"}
)
func tokenFromEnv() (string, error) {
ts, err := google.DefaultTokenSource(context.Background(), scopes...)
if err != nil {
return "", err
}
token, err := ts.Token()
if err != nil {
return "", err
}
if !token.Valid() {
return "", fmt.Errorf("token was invalid", nil)
}
if token.Type() != "Bearer" {
return "", fmt.Errorf("expected token type \"Bearer\" but got \"%s\"", token.Type())
}
return token.Extra("id_token").(string), nil
}
func main() {
client := &http.Client{}
id_token, err := tokenFromEnv()
if err != nil {
fmt.Errorf("token: %v", err)
}
req, err := http.NewRequest("GET", "https://my-endpoint.example.com/", nil)
if err != nil {
fmt.Errorf("req: %v", err)
}
req.Header.Add("Authorization", "Bearer "+id_token)
resp, err := client.Do(req)
if err != nil {
fmt.Errorf("Error when calling: %s", err)
}
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("Response from server: %s", string(body))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment