Reuse Token for serviceAccount credentials (#1238)
This commit is contained in:
@ -37,6 +37,7 @@ package oauth
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"golang.org/x/net/context"
|
"golang.org/x/net/context"
|
||||||
"golang.org/x/oauth2"
|
"golang.org/x/oauth2"
|
||||||
@ -132,20 +133,27 @@ func NewComputeEngine() credentials.PerRPCCredentials {
|
|||||||
|
|
||||||
// serviceAccount represents PerRPCCredentials via JWT signing key.
|
// serviceAccount represents PerRPCCredentials via JWT signing key.
|
||||||
type serviceAccount struct {
|
type serviceAccount struct {
|
||||||
|
mu sync.Mutex
|
||||||
config *jwt.Config
|
config *jwt.Config
|
||||||
|
t *oauth2.Token
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s serviceAccount) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
|
func (s *serviceAccount) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
|
||||||
token, err := s.config.TokenSource(ctx).Token()
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
if !s.t.Valid() {
|
||||||
|
var err error
|
||||||
|
s.t, err = s.config.TokenSource(ctx).Token()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return map[string]string{
|
return map[string]string{
|
||||||
"authorization": token.TokenType + " " + token.AccessToken,
|
"authorization": s.t.TokenType + " " + s.t.AccessToken,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s serviceAccount) RequireTransportSecurity() bool {
|
func (s *serviceAccount) RequireTransportSecurity() bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -156,7 +164,7 @@ func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.PerR
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return serviceAccount{config: config}, nil
|
return &serviceAccount{config: config}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewServiceAccountFromFile constructs the PerRPCCredentials using the JSON key file
|
// NewServiceAccountFromFile constructs the PerRPCCredentials using the JSON key file
|
||||||
|
Reference in New Issue
Block a user