原始碼 grpc 認證 鴨子模型 函式返回值為介面
阿新 • • 發佈:2021-12-21
原始碼 grpc 認證 鴨子模型
Authentication | gRPC https://www.grpc.io/docs/guides/auth/#authenticate-with-google
將谷歌的認證實現,改成定義的認證實現
perRPC, _ := oauth.NewServiceAccountFromFile("service-account.json", scope)
google.golang.org/[email protected]/credentials/oauth/oauth.go:192
// NewServiceAccountFromFile constructs the PerRPCCredentials using the JSON key file
// of a Google Developers service account.
func NewServiceAccountFromFile(keyFile string, scope ...string) (credentials.PerRPCCredentials, error) {
jsonKey, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err)
}
return NewServiceAccountFromKey(jsonKey, scope...)
}
關注返回值
google.golang.org/[email protected]/credentials/credentials.go:38
// PerRPCCredentials defines the common interface for the credentials which need to
// attach security information to every RPC (e.g., oauth2).
type PerRPCCredentials interface {
// GetRequestMetadata gets the current request metadata, refreshing
// tokens if required. This should be called by the transport layer on
// each request, and the data should be populated in headers or other
// context. If a status code is returned, it will be used as the status
// for the RPC. uri is the URI of the entry point for the request.
// When supported by the underlying implementation, ctx can be used for
// timeout and cancellation. Additionally, RequestInfo data will be
// available via ctx to this call.
// TODO(zhaoq): Define the set of the qualified keys instead of leaving
// it as an arbitrary string.
GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
// RequireTransportSecurity indicates whether the credentials requires
// transport security.
RequireTransportSecurity() bool
}
其中原返回值為Google的邏輯
// NewServiceAccountFromKey constructs the PerRPCCredentials using the JSON key slice
// from a Google Developers service account.
func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.PerRPCCredentials, error) {
config, err := google.JWTConfigFromJSON(jsonKey, scope...)
if err != nil {
return nil, err
}
return &serviceAccount{config: config}, nil
}
實現方法
type T struct {
}
func NewCustomerPerRPCCredentials() (PerRPCCredentials, error) {
return &T{}, nil
}
func (t *T) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return nil, nil
}
func (t *T) RequireTransportSecurity() bool {
return true
}
perRPC, err := NewCustomerPerRPCCredentials()
鴨子能走路,能走路的就是鴨子。