forked from golang/oauth2
/
credential.go
53 lines (48 loc) · 1.63 KB
/
credential.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package oauth2
import (
"context"
"errors"
)
// PerRPCCredentials fulfills the grpc PerRPCCredentials interface allowing
// a developer to use a Tokensource for authorization.
//
// target := "firestore.googleapis.com:443"
// ctx := context.Background()
// ts, err := getTokensourceFromFile("/path/to/your-project-key.json",
// "https://www.googleapis.com/auth/datastore", "https://www.googleapis.com/auth/cloud-platform")
// if err != nil {
// log.Fatalf("%v", err)
// }
// conn, err := grpc.DialContext(ctx, target,
// grpc.WithPerRPCCredentials(&oauth2.PerRPCCredentials{
// TokenSource: ts,
// }),
// grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
// )
// conn.WaitForStateChange(ctx, connectivity.Ready)
// cl, err := firestore.NewClient(ctx, "my-firestore-project", option.WithGRPCConn(conn))
// if err != nil {
// log.Fatalf("%v", err)
// }
//
type PerRPCCredentials struct {
TokenSource
}
// GetRequestMetadata returns authorization headers for a grpc credential
func (c *PerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
if c == nil || c.TokenSource == nil {
return nil, errors.New("nil credential")
}
tk, err := c.Token(ctx)
if err != nil {
return nil, err
}
return map[string]string{"authorization": tk.Type() + " " + tk.AccessToken}, nil
}
// RequireTransportSecurity needed for google.golang.org/grpc/credential
func (c *PerRPCCredentials) RequireTransportSecurity() bool {
return true
}