本文整理汇总了Golang中google/golang.org/grpc.WithPerRPCCredentials函数的典型用法代码示例。如果您正苦于以下问题:Golang WithPerRPCCredentials函数的具体用法?Golang WithPerRPCCredentials怎么用?Golang WithPerRPCCredentials使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了WithPerRPCCredentials函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewRoloClient
func NewRoloClient(idToken jose.JWT, tls bool, addr, serverHostOverride, trustedCaFile string) (*RoloClient, error) {
var opts []grpc.DialOption
creds := grpcoidc.NewOIDCAccess(&idToken)
opts = append(opts, grpc.WithPerRPCCredentials(creds))
if tls {
var sn string
if serverHostOverride != "" {
sn = serverHostOverride
}
var creds credentials.TransportAuthenticator
if trustedCaFile != "" {
var err error
creds, err = credentials.NewClientTLSFromFile(trustedCaFile, sn)
if err != nil {
return nil, err
}
}
opts = append(opts, grpc.WithTransportCredentials(creds))
}
conn, err := grpc.Dial(addr, opts...)
if err != nil {
return nil, err
}
return &RoloClient{
grpcClient: pb.NewRoloClient(conn),
}, nil
}
示例2: dial
func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
opts := c.dialSetupOpts(endpoint, dopts...)
host := getHost(endpoint)
if c.Username != "" && c.Password != "" {
// use dial options without dopts to avoid reusing the client balancer
auth, err := newAuthenticator(host, c.dialSetupOpts(endpoint))
if err != nil {
return nil, err
}
defer auth.close()
resp, err := auth.authenticate(c.ctx, c.Username, c.Password)
if err != nil {
return nil, err
}
opts = append(opts, grpc.WithPerRPCCredentials(authTokenCredential{token: resp.Token}))
}
// add metrics options
opts = append(opts, grpc.WithUnaryInterceptor(prometheus.UnaryClientInterceptor))
opts = append(opts, grpc.WithStreamInterceptor(prometheus.StreamClientInterceptor))
conn, err := grpc.Dial(host, opts...)
if err != nil {
return nil, err
}
return conn, nil
}
示例3: GRPCClient
func GRPCClient(addr, token, caFile string) (*RemoteU2FClient, error) {
var err error
var tCreds credentials.TransportCredentials
if caFile == "" {
tCreds = credentials.NewClientTLSFromCert(nil, "")
} else {
tCreds, err = credentials.NewClientTLSFromFile(caFile, "")
if err != nil {
return nil, fmt.Errorf("error reading CA file: %s", err)
}
}
t := oauth2.Token{
AccessToken: token,
TokenType: "Bearer",
}
rpcCreds := oauth.NewOauthAccess(&t)
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(tCreds),
grpc.WithPerRPCCredentials(rpcCreds),
grpc.WithBlock(),
grpc.WithTimeout(30*time.Second))
if err != nil {
return nil, fmt.Errorf("error connecting to server: %s", err)
}
c := pb.NewRemoteU2FClient(conn)
return &RemoteU2FClient{c}, nil
}
示例4: DialGRPC
// DialGRPC returns a GRPC connection for use communicating with a Google cloud
// service, configured with the given ClientOptions.
func DialGRPC(ctx context.Context, opt ...cloud.ClientOption) (*grpc.ClientConn, error) {
var o opts.DialOpt
for _, opt := range opt {
opt.Resolve(&o)
}
if o.HTTPClient != nil {
return nil, errors.New("unsupported HTTP base transport specified")
}
if o.GRPCClient != nil {
return o.GRPCClient, nil
}
if o.TokenSource == nil {
var err error
o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
if err != nil {
return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
}
}
grpcOpts := []grpc.DialOption{
grpc.WithPerRPCCredentials(oauth.TokenSource{o.TokenSource}),
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
}
grpcOpts = append(grpcOpts, o.GRPCDialOpts...)
if o.UserAgent != "" {
grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))
}
return grpc.Dial(o.Endpoint, grpcOpts...)
}
示例5: DialGRPC
// DialGRPC returns a GRPC connection for use communicating with a Google cloud
// service, configured with the given ClientOptions.
func DialGRPC(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {
var o internal.DialSettings
for _, opt := range opts {
opt.Apply(&o)
}
if o.HTTPClient != nil {
return nil, errors.New("unsupported HTTP client specified")
}
if o.GRPCConn != nil {
return o.GRPCConn, nil
}
if o.TokenSource == nil {
var err error
o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
if err != nil {
return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
}
}
grpcOpts := []grpc.DialOption{
grpc.WithPerRPCCredentials(oauth.TokenSource{o.TokenSource}),
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
}
if appengineDialerHook != nil {
// Use the Socket API on App Engine.
grpcOpts = append(grpcOpts, appengineDialerHook(ctx))
}
grpcOpts = append(grpcOpts, o.GRPCDialOpts...)
if o.UserAgent != "" {
grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))
}
return grpc.Dial(o.Endpoint, grpcOpts...)
}
示例6: TestCredentialsMisuse
func TestCredentialsMisuse(t *testing.T) {
creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com")
if err != nil {
t.Fatalf("Failed to create credentials %v", err)
}
// Two conflicting credential configurations
if _, err := grpc.Dial("Non-Existent.Server:80", grpc.WithTransportCredentials(creds), grpc.WithTimeout(time.Millisecond), grpc.WithBlock(), grpc.WithInsecure()); err != grpc.ErrCredentialsMisuse {
t.Fatalf("grpc.Dial(_, _) = _, %v, want _, %v", err, grpc.ErrCredentialsMisuse)
}
// security info on insecure connection
if _, err := grpc.Dial("Non-Existent.Server:80", grpc.WithPerRPCCredentials(creds), grpc.WithTimeout(time.Millisecond), grpc.WithBlock(), grpc.WithInsecure()); err != grpc.ErrCredentialsMisuse {
t.Fatalf("grpc.Dial(_, _) = _, %v, want _, %v", err, grpc.ErrCredentialsMisuse)
}
}
示例7: main
func main() {
var (
caCert = flag.String("ca-cert", withConfigDir("ca.pem"), "Trusted CA certificate.")
serverAddr = flag.String("server-addr", "127.0.0.1:7900", "Hello service address.")
tlsCert = flag.String("tls-cert", withConfigDir("cert.pem"), "TLS server certificate.")
tlsKey = flag.String("tls-key", withConfigDir("key.pem"), "TLS server key.")
token = flag.String("token", withConfigDir(".token"), "Path to JWT auth token.")
)
flag.Parse()
cert, err := tls.LoadX509KeyPair(*tlsCert, *tlsKey)
if err != nil {
log.Fatal(err)
}
rawCACert, err := ioutil.ReadFile(*caCert)
if err != nil {
log.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(rawCACert)
creds := credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
})
jwtCreds, err := jwt.NewFromTokenFile(*token)
if err != nil {
log.Fatal(err)
}
conn, err := grpc.Dial(*serverAddr,
grpc.WithTransportCredentials(creds),
grpc.WithPerRPCCredentials(jwtCreds))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
c := pb.NewHelloClient(conn)
message, err := c.Say(context.Background(), &pb.Request{"Kelsey"})
if err != nil {
log.Fatal(err)
}
log.Println(message.Message)
}
示例8: NewClient
// NewClient creates a new RPC connection to bmd.
func NewClient(cfg *ClientConfig, msg, broadcast, getpubkey func(counter uint64, msg []byte)) (*Client, error) {
opts := []grpc.DialOption{
grpc.WithPerRPCCredentials(
pb.NewBasicAuthCredentials(cfg.Username, cfg.Password)),
grpc.WithTimeout(cfg.Timeout)}
if !cfg.DisableTLS {
creds, err := credentials.NewClientTLSFromFile(cfg.CAFile, "")
if err != nil {
return nil, fmt.Errorf("Failed to create TLS credentials %v", err)
}
opts = append(opts, grpc.WithTransportCredentials(creds))
}
conn, err := grpc.Dial(cfg.ConnectTo, opts...)
if err != nil {
return nil, fmt.Errorf("Failed to dial: %v", err)
}
bmd := pb.NewBmdClient(conn)
// Verify credentials.
_, err = bmd.GetIdentity(context.Background(), &pb.GetIdentityRequest{
Address: "InvalidAddress",
})
code := grpc.Code(err)
if code == codes.Unauthenticated || code == codes.PermissionDenied {
return nil, errors.New("authentication failure; invalid username/password")
} else if code != codes.InvalidArgument {
return nil, fmt.Errorf("Unexpected error verifying credentials: %v", err)
}
return &Client{
bmd: bmd,
conn: conn,
quit: make(chan struct{}),
started: false,
msgFunc: msg,
broadcastFunc: broadcast,
getpubkeyFunc: getpubkey,
}, nil
}
示例9: connectRegistry
func connectRegistry(c *Config) {
var opts []grpc.DialOption
jwtCreds := newOauthAccess(c)
if discoveryServices.UseTls {
auth := credentials.NewClientTLSFromCert(nil, getServerName(discoveryServices.RegistryGrpc))
opts = append(opts, grpc.WithTransportCredentials(auth))
} else {
jwtCreds.RequireTLS = false
opts = append(opts, grpc.WithInsecure())
}
opts = append(opts, grpc.WithPerRPCCredentials(&jwtCreds))
registryConn, err := grpc.Dial(discoveryServices.RegistryGrpc, opts...)
if err != nil {
logrus.Fatalf("grpc.go: Error while connection to registry service %v\n", err)
}
registryClient = pb.NewRegistryServiceClient(registryConn)
}
示例10: DialGRPC
func DialGRPC(ctx context.Context, opts ...ClientOption) (*grpc.ClientConn, error) {
settings := &ClientSettings{}
clientOptions(opts).Resolve(settings)
if settings.Connection != nil {
return settings.Connection, nil
}
var dialOpts = settings.DialOptions
if len(dialOpts) == 0 {
tokenSource, err := google.DefaultTokenSource(ctx, settings.Scopes...)
if err != nil {
return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
}
dialOpts = []grpc.DialOption{
grpc.WithPerRPCCredentials(oauth.TokenSource{TokenSource: tokenSource}),
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
}
}
return grpc.Dial(settings.Endpoint, dialOpts...)
}
示例11: connect
func connect() {
var opts []grpc.DialOption
jwtCreds := NewOauthAccess(config())
if len(cafile) > 0 {
auth, err := credentials.NewClientTLSFromFile(cafile, "")
if err != nil {
panic(err)
} else {
opts = append(opts, grpc.WithTransportCredentials(auth))
}
} else {
jwtCreds.RequireTLS = false
opts = append(opts, grpc.WithInsecure())
}
opts = append(opts, grpc.WithPerRPCCredentials(&jwtCreds))
conn, err := grpc.Dial(remoteUrl, opts...)
if err != nil {
log.Fatalf("main.go: Error while connection to catalog service %v\n", err)
}
client = apipb.NewListenerServiceClient(conn)
}
示例12: ConnectToServices
func (c *OtsimoAccounts) ConnectToServices(dexServiceUrl, apiServiceUrl string) {
jwtCreds := NewOauthAccess(c.tm)
var opts []grpc.DialOption
if c.roots != nil {
opts = append(opts, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(c.roots, "")))
} else {
jwtCreds.RequireTLS = false
opts = append(opts, grpc.WithInsecure())
}
opts = append(opts, grpc.WithPerRPCCredentials(&jwtCreds))
conn, err := grpc.Dial(dexServiceUrl, opts...)
if err != nil {
log.Fatalf("Error while connection to dex service %v\n", err)
}
c.Dex = pb.NewDexServiceClient(conn)
apiConn, err := grpc.Dial(apiServiceUrl, opts...)
if err != nil {
log.Fatalf("Error while connection to api service %v\n", err)
}
c.Api = apipb.NewApiServiceClient(apiConn)
}
示例13: DialGRPC
// DialGRPC returns a GRPC connection for use communicating with a Google cloud
// service, configured with the given ClientOptions. Most developers should
// call the relevant NewClient method for the target service rather than
// invoking DialGRPC directly.
func DialGRPC(ctx context.Context, opt ...ClientOption) (*grpc.ClientConn, error) {
var o dialOpt
for _, opt := range opt {
opt.resolve(&o)
}
if o.httpClient != nil {
return nil, errors.New("unsupported HTTP base transport specified")
}
if o.grpcClient != nil {
return o.grpcClient, nil
}
if o.tokenSource == nil {
var err error
o.tokenSource, err = google.DefaultTokenSource(ctx, o.scopes...)
if err != nil {
return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
}
}
grpcOpts := []grpc.DialOption{
grpc.WithPerRPCCredentials(credentials.TokenSource{o.tokenSource}),
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
}
return grpc.Dial(o.endpoint, grpcOpts...)
}
示例14: main
func main() {
flag.Parse()
serverAddr := net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort))
var opts []grpc.DialOption
if *useTLS {
var sn string
if *tlsServerName != "" {
sn = *tlsServerName
}
var creds credentials.TransportAuthenticator
if *caFile != "" {
var err error
creds, err = credentials.NewClientTLSFromFile(*caFile, sn)
if err != nil {
log.Fatalf("Failed to create TLS credentials %v", err)
}
} else {
creds = credentials.NewClientTLSFromCert(nil, sn)
}
opts = append(opts, grpc.WithTransportCredentials(creds))
if *testCase == "compute_engine_creds" {
opts = append(opts, grpc.WithPerRPCCredentials(credentials.NewComputeEngine()))
} else if *testCase == "service_account_creds" {
jwtCreds, err := credentials.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope)
if err != nil {
log.Fatalf("Failed to create JWT credentials: %v", err)
}
opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
}
}
conn, err := grpc.Dial(serverAddr, opts...)
if err != nil {
log.Fatalf("Fail to dial: %v", err)
}
defer conn.Close()
tc := testpb.NewTestServiceClient(conn)
switch *testCase {
case "empty_unary":
doEmptyUnaryCall(tc)
case "large_unary":
doLargeUnaryCall(tc)
case "client_streaming":
doClientStreaming(tc)
case "server_streaming":
doServerStreaming(tc)
case "ping_pong":
doPingPong(tc)
case "compute_engine_creds":
if !*useTLS {
log.Fatalf("TLS is not enabled. TLS is required to execute compute_engine_creds test case.")
}
doComputeEngineCreds(tc)
case "service_account_creds":
if !*useTLS {
log.Fatalf("TLS is not enabled. TLS is required to execute service_account_creds test case.")
}
doServiceAccountCreds(tc)
default:
log.Fatal("Unsupported test case: ", *testCase)
}
}
示例15: main
func main() {
flag.Parse()
q := ParseQuery(*queryFlag, *delimiter)
if len(q.Queries) == 0 {
log.Fatal("--query must be set")
}
q.Target = *targetFlag
if *tlsFlag {
var sn string
if *serverHostOverride != "" {
sn = *serverHostOverride
} else {
sn = q.Target
}
var creds credentials.TransportCredentials
if *caFile != "" {
var err error
creds, err = credentials.NewClientTLSFromFile(*caFile, sn)
if err != nil {
log.Fatalf("Failed to create TLS credentials %v\n", err)
}
} else {
creds = credentials.NewTLS(&tls.Config{
ServerName: sn,
InsecureSkipVerify: true,
})
}
q.DialOptions = append(q.DialOptions, grpc.WithTransportCredentials(creds))
} else {
q.DialOptions = append(q.DialOptions, grpc.WithInsecure())
}
if *user != "" {
pc := credential.NewPassCred(*user, *passwd, true)
q.DialOptions = append(q.DialOptions, grpc.WithPerRPCCredentials(pc))
}
if *outfile != "" {
f, err := os.Create(*outfile)
var fMu sync.Mutex
if err != nil {
log.Fatalf("Failed to open file %s: %s", *outfile, err)
}
cfg.Display = func(b []byte) {
fMu.Lock()
defer fMu.Unlock()
n := make([]byte, len(b)+1)
n[copy(n, b)] = byte('\n')
f.Write(n)
}
}
switch {
case q.Update != nil:
if err := query.Update(context.Background(), q, &cfg); err != nil {
log.Infof("query.Update failed for query %v %v: %s\n", cfg, q, err)
}
case len(q.Queries) > 0 && *subscribe:
cfg.Once = *subscribeOnce
if err := query.DisplayStream(context.Background(), q, &cfg); err != nil {
log.Infof("query.DisplayStream failed for query %v %v: %s\n", cfg, q, err)
}
default:
if err := query.Display(context.Background(), q, &cfg); err != nil {
log.Infof("query.Display failed for query %v %v: %s\n", cfg, q, err)
}
}
}