gRPC 提供通用的机制(后续进行描述)来对请求和应答附加基于元数据的凭证。当通过 gRPC 访问 Google API 时,会为一定的授权流程提供额外的获取访问令牌的支持,这将通过以下代码例子进行展示。 警告:Google OAuth2 凭证应该仅用于连接 Google 的服务。把 Google 对应的 OAuth2 令牌发往非 Google 的服务会导致令牌被窃取用作冒充客户端来访问 Google 的服务。
// Create a default SSL ChannelCredentials object. auto channel_creds = grpc::SslCredentials(grpc::SslCredentialsOptions()); // Create a channel using the credentials created in the previous step. auto channel = grpc::CreateChannel(server_name, creds); // Create a stub on the channel. std::unique_ptr<Greeter::Stub> stub(Greeter::NewStub(channel)); // Make actual RPC calls on the stub. grpc::Status s = stub->sayHello(&context, *request, response);
对于高级的用例比如改变根 CA 或使用客户端证书,可以在发送给工厂方法的 SslCredentialsOptions 参数里的相应选项进行设置。
通过 Google 进行认证
gRPC应用可以使用一个简单的API来创建一个可以工作在不同部署场景下的凭证。
1 2 3 4 5
auto creds = grpc::GoogleDefaultCredentials(); // Create a channel, stub and make RPC calls (same as in the previous example) auto channel = grpc::CreateChannel(server_name, creds); std::unique_ptr<Greeter::Stub> stub(Greeter::NewStub(channel)); grpc::Status s = stub->sayHello(&context, *request, response);
creds = GRPC::Core::Credentials.new(load_certs) # load_certs typically loads a CA roots file stub = Helloworld::Greeter::Stub.new('myservice.example.com', creds)
通过Google验证
1 2 3 4 5 6 7
require'googleauth'# from http://www.rubydoc.info/gems/googleauth/0.1.0 ... ssl_creds = GRPC::Core::ChannelCredentials.new(load_certs) # load_certs typically loads a CA roots file authentication = Google::Auth.get_application_default() call_creds = GRPC::Core::CallCredentials.new(authentication.updater_proc) combined_creds = ssl_creds.compose(call_creds) stub = Helloworld::Greeter::Stub.new('greeter.googleapis.com', combined_creds)
C++
基本情况 - 无加密或身份验证
1 2 3
auto channel = grpc::CreateChannel("localhost:50051", InsecureChannelCredentials()); std::unique_ptr<Greeter::Stub> stub(Greeter::NewStub(channel)); ...
使用服务器身份验证SSL / TLS
1 2 3 4
auto channel_creds = grpc::SslCredentials(grpc::SslCredentialsOptions()); auto channel = grpc::CreateChannel("myservice.example.com", channel_creds); std::unique_ptr<Greeter::Stub> stub(Greeter::NewStub(channel)); ...
A通过Google验证
1 2 3 4
auto creds = grpc::GoogleDefaultCredentials(); auto channel = grpc::CreateChannel("greeter.googleapis.com", creds); std::unique_ptr<Greeter::Stub> stub(Greeter::NewStub(channel)); ...
C#
基本情况 - 无加密或身份验证
1 2 3
var channel = new Channel("localhost:50051", ChannelCredentials.Insecure); var client = new Greeter.GreeterClient(channel); ...
使用服务器身份验证SSL / TLS
1 2 3
var channelCredentials = new SslCredentials(File.ReadAllText("roots.pem")); // Load a custom roots file. var channel = new Channel("myservice.example.com", channelCredentials); var client = new Greeter.GreeterClient(channel);
A通过Google验证
1 2 3 4 5 6 7 8
using Grpc.Auth; // from Grpc.Auth NuGet package ... // Loads Google Application Default Credentials with publicly trusted roots. var channelCredentials = await GoogleGrpcCredentials.GetApplicationDefaultAsync();
var channel = new Channel("greeter.googleapis.com", channelCredentials); var client = new Greeter.GreeterClient(channel); ...
验证单个RPC调用
1 2 3 4 5 6
var channel = new Channel("greeter.googleapis.com", new SslCredentials()); // Use publicly trusted roots. var client = new Greeter.GreeterClient(channel); ... var googleCredential = await GoogleCredential.GetApplicationDefaultAsync(); var result = client.SayHello(request, new CallOptions(credentials: googleCredential.ToCallCredentials())); ...
import grpc import helloworld_pb2 from concurrent import futures
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) withopen('key.pem', 'rb') as f: private_key = f.read() withopen('chain.pem', 'rb') as f: certificate_chain = f.read() server_credentials = grpc.ssl_server_credentials( ( (private_key, certificate_chain), ) ) # Adding GreeterServicer to server omitted server.add_secure_port('myservice.example.com:443', server_credentials) server.start() # Server sleep omitted
使用JWT与Google进行身份验证
1 2 3 4 5 6 7 8 9 10 11 12 13
import grpc import helloworld_pb2
from google import auth as google_auth from google.auth import jwt as google_auth_jwt from google.auth.transport import grpc as google_auth_transport_grpc
from google import auth as google_auth from google.auth.transport import grpc as google_auth_transport_grpc from google.auth.transport import requests as google_auth_transport_requests
// With server authentication SSL/TLS ManagedChannelchannel= ManagedChannelBuilder.forAddress("myservice.example.com", 443) .build(); GreeterGrpc.GreeterStubstub= GreeterGrpc.newStub(channel);
// With server authentication SSL/TLS; custom CA root certificates; not on Android ManagedChannelchannel= NettyChannelBuilder.forAddress("myservice.example.com", 443) .sslContext(GrpcSslContexts.forClient().trustManager(newFile("roots.pem")).build()) .build(); GreeterGrpc.GreeterStubstub= GreeterGrpc.newStub(channel);
通过Google验证
The following code snippet shows how you can call the Google Cloud PubSub API using gRPC with a service account. The credentials are loaded from a key stored in a well-known location or by detecting that the application is running in an environment that can provide one automatically, e.g. Google Compute Engine. While this example is specific to Google and its services, similar patterns can be followed for other service providers.
var stub = new helloworld.Greeter('localhost:50051', grpc.credentials.createInsecure());
使用服务器身份验证SSL / TLS
1 2
var ssl_creds = grpc.credentials.createSsl(root_certs); var stub = new helloworld.Greeter('myservice.example.com', ssl_creds);
通过Google验证
1 2 3 4 5 6 7 8 9
// Authenticating with Google varGoogleAuth = require('google-auth-library'); // from https://www.npmjs.com/package/google-auth-library ... var ssl_creds = grpc.credentials.createSsl(root_certs); (newGoogleAuth()).getApplicationDefault(function(err, auth) { var call_creds = grpc.credentials.createFromGoogleCredential(auth); var combined_creds = grpc.credentials.combineChannelCredentials(ssl_creds, call_creds); var stub = new helloworld.Greeter('greeter.googleapis.com', combined_credentials); });
使用Oauth2令牌使用Google进行身份验证(传统方法)
1 2 3 4 5 6 7 8 9 10 11 12
varGoogleAuth = require('google-auth-library'); // from https://www.npmjs.com/package/google-auth-library ... var ssl_creds = grpc.Credentials.createSsl(root_certs); // load_certs typically loads a CA roots file var scope = 'https://www.googleapis.com/auth/grpc-testing'; (newGoogleAuth()).getApplicationDefault(function(err, auth) { if (auth.createScopeRequired()) { auth = auth.createScoped(scope); } var call_creds = grpc.credentials.createFromGoogleCredential(auth); var combined_creds = grpc.credentials.combineChannelCredentials(ssl_creds, call_creds); var stub = new helloworld.Greeter('greeter.googleapis.com', combined_credentials); });
PHP
基本情况 - 无加密或身份验证
1 2 3 4
$client = new helloworld\GreeterClient('localhost:50051', [ 'credentials' => Grpc\ChannelCredentials::createInsecure(), ]); ...
// the environment variable "GOOGLE_APPLICATION_CREDENTIALS" needs to be set $scope = "https://www.googleapis.com/auth/grpc-testing"; $auth = Google\Auth\ApplicationDefaultCredentials::getCredentials($scope); $opts = [ 'credentials' => Grpc\Credentials::createSsl(file_get_contents('roots.pem')); 'update_metadata' => $auth->getUpdateMetadataFunc(), ]; $client = new helloworld\GreeterClient('greeter.googleapis.com', $opts);
Dart
基本情况 - 无加密或身份验证
1 2 3 4 5
final channel = new ClientChannel('localhost', port: 50051, options: const ChannelOptions( credentials: const ChannelCredentials.insecure())); final stub = new GreeterClient(channel);
使用服务器身份验证SSL / TLS
1 2 3 4 5 6 7 8
// Load a custom roots file. final trustedRoot = new File('roots.pem').readAsBytesSync(); final channelCredentials = new ChannelCredentials.secure(certificates: trustedRoot); final channelOptions = new ChannelOptions(credentials: channelCredentials); final channel = new ClientChannel('myservice.example.com', options: channelOptions); final client = new GreeterClient(channel);
通过Google验证
1 2 3 4 5 6 7
// Uses publicly trusted roots by default. final channel = new ClientChannel('greeter.googleapis.com'); final serviceAccountJson = new File('service-account.json').readAsStringSync(); final credentials = new JwtServiceAccountAuthenticator(serviceAccountJson); final client = new GreeterClient(channel, options: credentials.toCallOptions);
验证单个RPC调用
1 2 3 4 5 6 7 8 9
// Uses publicly trusted roots by default. final channel = new ClientChannel('greeter.googleapis.com'); final client = new GreeterClient(channel); ... final serviceAccountJson = new File('service-account.json').readAsStringSync(); final credentials = new JwtServiceAccountAuthenticator(serviceAccountJson); final response = await client.sayHello(request, options: credentials.toCallOptions);