GoogleCloudPlatform / GoogleCloudPlatform/golang-samples

Tokens expire after 1 hour - use Tokensource instead.

Open
#2,139 2 comments 0 reactions 1 assignee Assigned to @grayside View on GitHub
api: run priority: p2 samples stale: old type: feature request
Dominant language
Go
Stars
4.7k
Forks
1.9k
Avg merge
3d 14h
Merged PRs (30d)
44

Description

https://github.com/GoogleCloudPlatform/golang-samples/blob/42a8597d5beb089c313eb618ac1363af5e404be0/run/grpc-ping/connection.go#L30

The current example manually adds a token to each client request. For some longer running services, this becomes an issue since the client is usually instantiated when launching the service, requests made after 1 hour of the initial client instantiation will fail since the token will have expired by then.

Rather use the TokenSource methodology where the underlying token is validated and only refreshed when needed.

Here is a revised `NewConn` method illustrating a potential solution to the above:
```go
type grpcTokenSource struct {
oauth.TokenSource
}

// NewConn creates a new gRPC connection.
// host should be of the form domain:port, e.g., example.com:443
func NewConn(ctx context.Context, host string, insecure bool) (*grpc.ClientConn, error) {
var opts []grpc.DialOption
if host != "" {
opts = append(opts, grpc.WithAuthority(host))
}

if insecure {
opts = append(opts, grpc.WithInsecure())
} else {
systemRoots, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
cred := credentials.NewTLS(&tls.Config{
RootCAs: systemRoots,
})
opts = append(opts, grpc.WithTransportCredentials(cred))
}

// use a tokenSource to automatically inject tokens with each underlying client request
audience := "https://" + strings.Split(host, ":")[0]
tokenSource, err := idtoken.NewTokenSource(ctx, audience, option.WithAudiences(audience))
if err != nil {
return nil, status.Errorf(
codes.Unauthenticated,
"NewTokenSource: %s", err,
)
}
opts = append(opts, grpc.WithPerRPCCredentials(grpcTokenSource{
TokenSource: oauth.TokenSource{
tokenSource,
},
}))

return grpc.Dial(host, opts...)
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.