Created
November 6, 2018 08:43
-
-
Save lsjostro/53fcec5932a607e815cfde36017b1d72 to your computer and use it in GitHub Desktop.
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" | |
api "github.com/example/pb" | |
"golang.org/x/oauth2" | |
"golang.org/x/oauth2/google" | |
"google.golang.org/grpc" | |
"google.golang.org/grpc/credentials" | |
) | |
type tokenSource struct { | |
oauth2.TokenSource | |
} | |
func NewOauthAccess(src oauth2.TokenSource) credentials.PerRPCCredentials { | |
return tokenSource{src} | |
} | |
func (ts tokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { | |
token, err := ts.Token() | |
if err != nil { | |
return nil, err | |
} | |
if !token.Valid() { | |
return nil, fmt.Errorf("token was invalid", nil) | |
} | |
if token.Type() != "Bearer" { | |
return nil, fmt.Errorf("expected token type \"Bearer\" but got \"%s\"", token.Type()) | |
} | |
return map[string]string{ | |
"authorization": token.Type() + " " + token.Extra("id_token").(string), | |
}, nil | |
} | |
func (ts tokenSource) RequireTransportSecurity() bool { | |
return true | |
} | |
var ( | |
hostAndPort = "my-endpoint.example.com:443" | |
scopes = []string{"https://www.googleapis.com/auth/cloud-platform"} | |
) | |
func main() { | |
ts, err := google.DefaultTokenSource(context.Background(), scopes...) | |
if err != nil { | |
fmt.Printf("token: %v", err) | |
return | |
} | |
creds := credentials.NewClientTLSFromCert(nil, "my-endpoint.example.com") | |
conn, err := grpc.Dial(hostAndPort, []grpc.DialOption{ | |
grpc.WithPerRPCCredentials(NewOauthAccess(ts)), | |
grpc.WithTransportCredentials(creds), | |
}...) | |
if err != nil { | |
fmt.Printf("dial: %v", err) | |
return | |
} | |
c := api.NewGrpcClient(conn) | |
response, err := c.SomeMethod(context.Background(), &api.SomeMethodRequest{Foo: []string{"bar"}}) | |
if err != nil { | |
fmt.Printf("Error when calling SomeMethod: %s", err) | |
return | |
} | |
fmt.Printf("Response from server: %s", response) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment