• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang grpc.WithPerRPCCredentials函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中google/golang.org/grpc.WithPerRPCCredentials函数的典型用法代码示例。如果您正苦于以下问题:Golang WithPerRPCCredentials函数的具体用法?Golang WithPerRPCCredentials怎么用?Golang WithPerRPCCredentials使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了WithPerRPCCredentials函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:polvi,项目名称:rolo,代码行数:27,代码来源:client.go


示例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
}
开发者ID:RichardKnop,项目名称:go-oauth2-server,代码行数:28,代码来源:client.go


示例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
}
开发者ID:albertito,项目名称:remoteu2f,代码行数:29,代码来源:grpc.go


示例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...)
}
开发者ID:otsimo,项目名称:watch,代码行数:30,代码来源:dial.go


示例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...)
}
开发者ID:Ropes,项目名称:pubbing,代码行数:34,代码来源:dial.go


示例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)
	}
}
开发者ID:johnmccawley,项目名称:origin,代码行数:14,代码来源:end2end_test.go


示例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)
}
开发者ID:kelseyhightower,项目名称:grpc-hello-service,代码行数:48,代码来源:main.go


示例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
}
开发者ID:DanielKrawisz,项目名称:bmagent,代码行数:44,代码来源:client.go


示例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)
}
开发者ID:otsimo,项目名称:otsimoctl,代码行数:19,代码来源:grpc.go


示例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...)
}
开发者ID:vburenin,项目名称:firempq,代码行数:20,代码来源:dial.go


示例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)
}
开发者ID:otsimo,项目名称:listener,代码行数:22,代码来源:main.go


示例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)
}
开发者ID:otsimo,项目名称:accounts,代码行数:23,代码来源:accounts.go


示例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...)
}
开发者ID:rizzles,项目名称:convert,代码行数:28,代码来源:option.go


示例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)
	}
}
开发者ID:gameduell,项目名称:kythe,代码行数:61,代码来源:client.go


示例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)
		}
	}
}
开发者ID:openconfig,项目名称:reference,代码行数:65,代码来源:main.go


示例16: 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.TransportCredentials
		if *testCA {
			var err error
			creds, err = credentials.NewClientTLSFromFile(testCAFile, sn)
			if err != nil {
				grpclog.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(oauth.NewComputeEngine()))
		} else if *testCase == "service_account_creds" {
			jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope)
			if err != nil {
				grpclog.Fatalf("Failed to create JWT credentials: %v", err)
			}
			opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
		} else if *testCase == "jwt_token_creds" {
			jwtCreds, err := oauth.NewJWTAccessFromFile(*serviceAccountKeyFile)
			if err != nil {
				grpclog.Fatalf("Failed to create JWT credentials: %v", err)
			}
			opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
		} else if *testCase == "oauth2_auth_token" {
			opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewOauthAccess(interop.GetToken(*serviceAccountKeyFile, *oauthScope))))
		}
	} else {
		opts = append(opts, grpc.WithInsecure())
	}
	conn, err := grpc.Dial(serverAddr, opts...)
	if err != nil {
		grpclog.Fatalf("Fail to dial: %v", err)
	}
	defer conn.Close()
	tc := testpb.NewTestServiceClient(conn)
	switch *testCase {
	case "empty_unary":
		interop.DoEmptyUnaryCall(tc)
		grpclog.Println("EmptyUnaryCall done")
	case "large_unary":
		interop.DoLargeUnaryCall(tc)
		grpclog.Println("LargeUnaryCall done")
	case "client_streaming":
		interop.DoClientStreaming(tc)
		grpclog.Println("ClientStreaming done")
	case "server_streaming":
		interop.DoServerStreaming(tc)
		grpclog.Println("ServerStreaming done")
	case "ping_pong":
		interop.DoPingPong(tc)
		grpclog.Println("Pingpong done")
	case "empty_stream":
		interop.DoEmptyStream(tc)
		grpclog.Println("Emptystream done")
	case "timeout_on_sleeping_server":
		interop.DoTimeoutOnSleepingServer(tc)
		grpclog.Println("TimeoutOnSleepingServer done")
	case "compute_engine_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute compute_engine_creds test case.")
		}
		interop.DoComputeEngineCreds(tc, *defaultServiceAccount, *oauthScope)
		grpclog.Println("ComputeEngineCreds done")
	case "service_account_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute service_account_creds test case.")
		}
		interop.DoServiceAccountCreds(tc, *serviceAccountKeyFile, *oauthScope)
		grpclog.Println("ServiceAccountCreds done")
	case "jwt_token_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute jwt_token_creds test case.")
		}
		interop.DoJWTTokenCreds(tc, *serviceAccountKeyFile)
		grpclog.Println("JWTtokenCreds done")
	case "per_rpc_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute per_rpc_creds test case.")
		}
		interop.DoPerRPCCreds(tc, *serviceAccountKeyFile, *oauthScope)
		grpclog.Println("PerRPCCreds done")
	case "oauth2_auth_token":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute oauth2_auth_token test case.")
		}
		interop.DoOauth2TokenCreds(tc, *serviceAccountKeyFile, *oauthScope)
		grpclog.Println("Oauth2TokenCreds done")
	case "cancel_after_begin":
		interop.DoCancelAfterBegin(tc)
//.........这里部分代码省略.........
开发者ID:tamird,项目名称:grpc-go,代码行数:101,代码来源:client.go


示例17: Dial

// Dial establishes a connection for a given endpoint using the client's config
func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
	opts := []grpc.DialOption{
		grpc.WithBlock(),
		grpc.WithTimeout(c.cfg.DialTimeout),
	}

	proto := "tcp"
	creds := c.creds
	if url, uerr := url.Parse(endpoint); uerr == nil && strings.Contains(endpoint, "://") {
		switch url.Scheme {
		case "unix":
			proto = "unix"
		case "http":
			creds = nil
		case "https":
			if creds == nil {
				tlsconfig := &tls.Config{InsecureSkipVerify: true}
				emptyCreds := credentials.NewTLS(tlsconfig)
				creds = &emptyCreds
			}
		default:
			return nil, fmt.Errorf("unknown scheme %q for %q", url.Scheme, endpoint)
		}
		// strip scheme:// prefix since grpc dials by host
		endpoint = url.Host
	}
	f := func(a string, t time.Duration) (net.Conn, error) {
		select {
		case <-c.ctx.Done():
			return nil, c.ctx.Err()
		default:
		}
		return net.DialTimeout(proto, a, t)
	}
	opts = append(opts, grpc.WithDialer(f))

	if creds != nil {
		opts = append(opts, grpc.WithTransportCredentials(*creds))
	} else {
		opts = append(opts, grpc.WithInsecure())
	}

	if c.Username != "" && c.Password != "" {
		auth, err := newAuthenticator(endpoint, opts)
		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}))
	}

	conn, err := grpc.Dial(endpoint, opts...)
	if err != nil {
		return nil, err
	}
	return conn, nil
}
开发者ID:XiangrongFan,项目名称:etcd,代码行数:64,代码来源:client.go


示例18:

		grpc.WithCodec(GRPCCodec),
	}

	grpcEndpoint := GRPCEndpoint(ctx)
	if grpcEndpoint.Scheme == "https" {
		creds := credentials.NewClientTLSFromCert(nil, "")
		if host, _, _ := net.SplitHostPort(grpcEndpoint.Host); host == "localhost" {
			creds = credentials.NewTLS(&tls.Config{InsecureSkipVerify: true})
		}
		opts = append(opts, grpc.WithTransportCredentials(creds))
	}

	// Use contextCredentials instead of directly using the cred
	// so that we can use different credentials for the same
	// connection (in the pool).
	opts = append(opts, grpc.WithPerRPCCredentials(contextCredentials{}))

	// Dial timeout is the lesser of the ctx deadline or
	// maxDialTimeout.
	var timeout time.Duration
	if d, ok := ctx.Deadline(); ok && time.Now().Add(maxDialTimeout).After(d) {
		timeout = d.Sub(time.Now())
	} else {
		timeout = maxDialTimeout
	}
	opts = append(opts, grpc.WithTimeout(timeout))

	conn, err := pooledGRPCDial(grpcEndpoint.Host, opts...)
	if err != nil {
		panic(err)
	}
开发者ID:alexsaveliev,项目名称:go-sourcegraph,代码行数:31,代码来源:context.go


示例19: init

func init() {
	UI = &cli.BasicUi{Writer: os.Stdout, Reader: os.Stdin}

	user, err := user.Current()
	if err != nil {
		UI.Error(err.Error())
		os.Exit(1)
	}

	configPath := path.Join(user.HomeDir, command.ConfigFileName)

	c, err := command.ParseConfigFile(configPath)
	if err != nil {
		UI.Error(err.Error())
		os.Exit(1)
	}

	Configuration = c

	var db olddata.DB
	var databaseError error

	if Configuration.DirectDB {
		if Configuration.DB != "" {
			db, databaseError = models.MongoDB(Configuration.DB)
		} else {
			databaseError = fmt.Errorf("No database listed")
		}
	} else {
		db = &gaia.DB{
			URL:      Configuration.Host,
			Username: Configuration.PublicCredential,
			Password: Configuration.PrivateCredential,
			Client:   new(http.Client),
		}
	}
	conn, err := grpc.Dial(
		"elos.pw:4444",
		grpc.WithPerRPCCredentials(
			auth.RawCredentials(
				Configuration.Credential.Public,
				Configuration.Credential.Private,
			),
		),
		grpc.WithInsecure(),
	)
	if err != nil {
		log.Fatal(err)
	}
	// don't close connection because we'd lose connection should
	// move declaration of dbc higher in scope TODO(nclandolfi)
	dbc := data.NewDBClient(conn)

	Commands = map[string]cli.CommandFactory{
		"habit": func() (cli.Command, error) {
			return &command.HabitCommand{
				UI:     UI,
				UserID: Configuration.UserID,
				DB:     db,
			}, databaseError
		},
		"people": func() (cli.Command, error) {
			return &command.PeopleCommand{
				UI:     UI,
				UserID: Configuration.UserID,
				DB:     db,
			}, databaseError
		},
		"setup": func() (cli.Command, error) {
			return &command.SetupCommand{
				UI:     UI,
				Config: Configuration,
			}, nil
		},
		"tag": func() (cli.Command, error) {
			return &command.TagCommand{
				UI:     UI,
				UserID: Configuration.UserID,
				DB:     db,
			}, databaseError
		},
		"stream": func() (cli.Command, error) {
			return &command.StreamCommand{
				UI:     UI,
				UserID: Configuration.UserID,
				DB:     db,
			}, databaseError
		},
		"todo": func() (cli.Command, error) {
			return &command.TodoCommand{
				UI:     UI,
				UserID: Configuration.Credential.OwnerID,
				DB:     data.DB(dbc),
			}, databaseError
		},
		"cal2": func() (cli.Command, error) {
			return &command.Cal2Command{
				UI:       UI,
				UserID:   Configuration.Credential.OwnerID,
				DBClient: dbc,
//.........这里部分代码省略.........
开发者ID:elos,项目名称:elos,代码行数:101,代码来源:init.go


示例20: connectClient

func connectClient(connect2registry, connect2catalog, connect2api bool) {

	discovery := os.Getenv("DEX_WORKER_ISSUER")

	cfg, err := oidc.FetchProviderConfig(http.DefaultClient, discovery)
	if err != nil {
		logrus.Fatalln("Unable to fetch provider configs")
	}

	ccfg := oidc.ClientConfig{
		ProviderConfig: cfg,
		Credentials:    cc,
	}

	//logrus.Printf("ccfg.Credentials: %+v",ccfg.Credentials)
	//logrus.Printf("ccfg.ProviderConfig: %+v",ccfg.ProviderConfig)

	myclient, err := oidc.NewClient(ccfg)
	if err != nil {
		logrus.Fatalf("Unable to create Client: %v", err)
	}

	tok, err := myclient.ClientCredsToken([]string{"openid"})
	if err != nil {
		logrus.Printf("Token: %+v ", tok)
		logrus.Errorf("Error: %+v", err)
		logrus.Fatalf("Unable to get token")
	}

	jwtCreds := NewOauthAccess(tok.Encode())
	//logrus.Println("got the jwtCreds")
	claims, err := tok.Claims()
	clientsub, _, _ = claims.StringClaim("sub")
	//logrus.Println("Get the clientsub", clientsub)

	if err != nil {
		logrus.Fatalln("unable to get getClientIdAndEmail", err)
	}

	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))

	if connect2api {
		apiUrl = os.Getenv("OTSIMO_SERVICES_API_URL")
		if apiUrl == "" {
			panic("OTSIMO_SERVICES_API_URL must set")
		}
		apiConn, _ := grpc.Dial(apiUrl, opts...)
		apiClient = apipb.NewApiServiceClient(apiConn)
		/*
			if err != nil {
				logrus.Println("                   cannot dial                    ")
				logrus.Println(err)
			} else {
				logrus.Println("                   dialed                         ")
			}

			if apiClient == nil {
				logrus.Println("                   apiClient error               ")
			} else {
				logrus.Println("                   apiClient                  ")
			}
		*/
	}
	//------------------------------------------------------------------------------------------------------------------
	if connect2registry {
		registryUrl = os.Getenv("OTSIMOCTL_REGISTRY")
		if registryUrl == "" {
			panic("OTSIMOCTL_REGISTRY must set")
		}

		regConn, _ := grpc.Dial(registryUrl, opts...)
		registryClient = apipb.NewRegistryServiceClient(regConn)
		/*
			if err != nil {
				logrus.Println("                   cannot dial                    ")
				logrus.Println(err)
			} else {
				logrus.Println("                   dialed                         ")
			}

			if registryClient == nil {
				logrus.Println("                   catalogClt error               ")
			} else {
				logrus.Println("                   catalogClient                  ")
			}
		*/
	}
	//------------------------------------------------------------------------------------------------------------------
	if connect2catalog {
//.........这里部分代码省略.........
开发者ID:otsimo,项目名称:integration-tests,代码行数:101,代码来源:connect.go



注:本文中的google/golang.org/grpc.WithPerRPCCredentials函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang grpc.WithPicker函数代码示例发布时间:2022-05-28
下一篇:
Golang grpc.WithInsecure函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap