### Example Service Config JSON Source: https://grpc.io/docs/guides/service-config This JSON configures the round_robin load balancing policy and sets default and specific method call timeouts. ```json { "loadBalancingConfig": [ { "round_robin": {} } ], "methodConfig": [ { "name": [{}], "timeout": "1s" }, { "name": [ { "service": "foo", "method": "bar" }, { "service": "baz" } ], "timeout": "2s" } ] } ``` -------------------------------- ### Client-side SSL/TLS Authentication in C++ Source: https://grpc.io/docs/guides/auth This snippet demonstrates how to create a channel with SSL/TLS credentials for server authentication and data encryption. It's suitable for basic client-side SSL/TLS setup. ```c++ // 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, channel_creds); // Create a stub on the channel. std::unique_ptr stub(Greeter::NewStub(channel)); // Make actual RPC calls on the stub. grpc::Status s = stub->sayHello(&context, *request, response); ``` -------------------------------- ### PHP: Base gRPC Client (No Encryption/Auth) Source: https://grpc.io/docs/guides/auth Basic PHP gRPC client setup for insecure connections. ```php $client = new helloworld GreeterClient('localhost:50051', [ 'credentials' => Grpc ChannelCredentials::createInsecure(), ]); ``` -------------------------------- ### Ruby: Base gRPC Client (No Encryption/Auth) Source: https://grpc.io/docs/guides/auth This is the most basic gRPC client setup in Ruby, used when no encryption or authentication is required. ```ruby stub = Helloworld::Greeter::Stub.new('localhost:50051', :this_channel_is_insecure) ... ``` -------------------------------- ### Ruby: gRPC Client Authenticating with Google Source: https://grpc.io/docs/guides/auth Set up a Ruby gRPC client to authenticate with Google services using application default credentials. Ensure the googleauth gem is installed. ```ruby 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) ``` -------------------------------- ### Implement Custom Metadata Credentials Plugin Source: https://grpc.io/docs/guides/auth Extend gRPC authentication by implementing the MetadataCredentialsPlugin to add custom headers to RPCs. This example shows how to set an authentication ticket in a custom header. ```C++ class MyCustomAuthenticator : public grpc::MetadataCredentialsPlugin { public: MyCustomAuthenticator(const grpc::string& ticket) : ticket_(ticket) {} grpc::Status GetMetadata( grpc::string_ref service_url, grpc::string_ref method_name, const grpc::AuthContext& channel_auth_context, std::multimap* metadata) override { metadata->insert(std::make_pair("x-custom-auth-ticket", ticket_)); return grpc::Status::OK; } private: grpc::string ticket_; }; auto call_creds = grpc::MetadataCredentialsFromPlugin( std::unique_ptr( new MyCustomAuthenticator("super-secret-ticket"))); ``` -------------------------------- ### Node.js: Base gRPC Client (No Encryption/Auth) Source: https://grpc.io/docs/guides/auth Basic Node.js gRPC client setup for connections without encryption or authentication. ```javascript var stub = new helloworld.Greeter('localhost:50051', grpc.credentials.createInsecure()); ``` -------------------------------- ### Node.js: gRPC Client Authenticating with Google (OAuth2 Legacy) Source: https://grpc.io/docs/guides/auth Legacy Node.js approach for authenticating gRPC clients with Google using OAuth2 tokens. Ensure the google-auth-library is installed. ```javascript var GoogleAuth = 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'; (new GoogleAuth()).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); }); ``` -------------------------------- ### gRPC Retry Throttling Configuration Source: https://grpc.io/docs/guides/retry Configures retry throttling to prevent server overload. This example sets the maximum number of tokens and the token ratio for managing retry attempts. ```json "retryThrottling": { "maxTokens": 10, "tokenRatio": 0.1 } ``` -------------------------------- ### PHP: gRPC Client Authenticating with Google (OAuth2 Legacy) Source: https://grpc.io/docs/guides/auth Legacy PHP approach for Google authentication using OAuth2 tokens. The GOOGLE_APPLICATION_CREDENTIALS environment variable must be set. ```php // 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); ``` -------------------------------- ### Node.js: gRPC Client Authenticating with Google Source: https://grpc.io/docs/guides/auth Node.js gRPC client authentication using Google's application default credentials. Requires the google-auth-library. ```javascript // Authenticating with Google var GoogleAuth = require('google-auth-library'); // from https://www.npmjs.com/package/google-auth-library ... var ssl_creds = grpc.credentials.createSsl(root_certs); (new GoogleAuth()).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); }); ``` -------------------------------- ### PHP: gRPC Client with Server SSL/TLS Authentication Source: https://grpc.io/docs/guides/auth PHP gRPC client configuration for SSL/TLS secured servers. Requires the 'roots.pem' certificate file. ```php $client = new helloworld GreeterClient('myservice.example.com', [ 'credentials' => Grpc ChannelCredentials::createSsl(file_get_contents('roots.pem')), ]); ``` -------------------------------- ### PHP: gRPC Client Authenticating with Google Source: https://grpc.io/docs/guides/auth Authenticate a PHP gRPC client with Google services using application default credentials. Requires the google/auth library. ```php function updateAuthMetadataCallback($context) { $auth_credentials = ApplicationDefaultCredentials::getCredentials(); return $auth_credentials->updateMetadata($metadata = [], $context->service_url); } $channel_credentials = Grpc ChannelCredentials::createComposite( Grpc ChannelCredentials::createSsl(file_get_contents('roots.pem')), Grpc CallCredentials::createFromPlugin('updateAuthMetadataCallback') ); $opts = [ 'credentials' => $channel_credentials ]; $client = new helloworld GreeterClient('greeter.googleapis.com', $opts); ``` -------------------------------- ### Node.js: gRPC Client with Server SSL/TLS Authentication Source: https://grpc.io/docs/guides/auth Node.js gRPC client configuration for servers using SSL/TLS. Requires reading the root certificate file. ```javascript const root_cert = fs.readFileSync('path/to/root-cert'); const ssl_creds = grpc.credentials.createSsl(root_cert); const stub = new helloworld.Greeter('myservice.example.com', ssl_creds); ``` -------------------------------- ### Ruby: gRPC Client with Server SSL/TLS Authentication Source: https://grpc.io/docs/guides/auth Configure a Ruby gRPC client to connect to a server secured with SSL/TLS. Requires loading CA certificates. ```ruby creds = GRPC::Core::ChannelCredentials.new(load_certs) # load_certs typically loads a CA roots file stub = Helloworld::Greeter::Stub.new('myservice.example.com', creds) ``` -------------------------------- ### Create Google Default Credentials Source: https://grpc.io/docs/guides/auth Use this to create channel credentials for authenticating with Google services, supporting Service Accounts and Google Compute Engine environments. The credentials automatically handle token generation and attachment to RPCs. ```C++ 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 stub(Greeter::NewStub(channel)); grpc::Status s = stub->sayHello(&context, *request, response); ``` -------------------------------- ### Node.js: gRPC Client with SSL/TLS and Custom Header Token Source: https://grpc.io/docs/guides/auth Configure a Node.js gRPC client with SSL/TLS and a custom authentication header. This is useful for custom token-based authentication schemes. ```javascript const rootCert = fs.readFileSync('path/to/root-cert'); const channelCreds = grpc.credentials.createSsl(rootCert); const metaCallback = (_params, callback) => { const meta = new grpc.Metadata(); meta.add('custom-auth-header', 'token'); callback(null, meta); } const callCreds = grpc.credentials.createFromMetadataGenerator(metaCallback); const combCreds = grpc.credentials.combineChannelCredentials(channelCreds, callCreds); const stub = new helloworld.Greeter('myservice.example.com', combCreds); ``` -------------------------------- ### Dart gRPC Client - Authenticate Single RPC Call Source: https://grpc.io/docs/guides/auth Demonstrates how to authenticate a single RPC call using Google service account credentials, while the channel itself might not be pre-authenticated. This is useful for making specific calls with elevated or different permissions. ```dart // 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); ``` -------------------------------- ### Dart gRPC Client - Server Authentication with SSL/TLS Source: https://grpc.io/docs/guides/auth Connects to a gRPC server using SSL/TLS for secure communication, authenticating the server using a custom set of trusted root certificates. Ensure 'roots.pem' contains the server's certificate chain. ```dart // 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); ``` -------------------------------- ### Dart gRPC Client - Authenticate with Google Service Account Source: https://grpc.io/docs/guides/auth Authenticates a gRPC client to Google services using a service account JSON key file. This method uses publicly trusted roots by default. The 'service-account.json' file must contain valid service account credentials. ```dart // 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); ``` -------------------------------- ### Configure Client Health Checking Source: https://grpc.io/docs/guides/health-checking Use this JSON configuration within the channel's service config to enable health checking for a specific service. The 'serviceName' should match the service you want to monitor. ```json { "healthCheckConfig": { "serviceName": "foo" } } ``` -------------------------------- ### gRPC Retry Policy Configuration Source: https://grpc.io/docs/guides/retry Defines the parameters for gRPC client-side retries. Use this to set the maximum number of attempts, initial and maximum backoff delays, the backoff multiplier, and the status codes that should trigger a retry. ```json "retryPolicy": { "maxAttempts": 4, "initialBackoff": "0.1s", "maxBackoff": "1s", "backoffMultiplier": 2, "retryableStatusCodes": [ "UNAVAILABLE" ] } ``` -------------------------------- ### Hedging Policy Configuration Source: https://grpc.io/docs/guides/request-hedging Configure hedging behavior for gRPC methods. Specify the maximum number of concurrent attempts, the delay between attempts, and status codes that should not trigger cancellation of other requests. ```json "hedgingPolicy": { "maxAttempts": INTEGER, "hedgingDelay": JSON proto3 Duration type, "nonFatalStatusCodes": JSON array of grpc status codes (int or string) } ``` -------------------------------- ### Dart gRPC Client - Insecure Channel Source: https://grpc.io/docs/guides/auth Establishes a basic gRPC client connection to a local server without any encryption or authentication. Use this for local development or testing environments. ```dart final channel = new ClientChannel('localhost', port: 50051, options: const ChannelOptions( credentials: const ChannelCredentials.insecure())); final stub = new GreeterClient(channel); ``` -------------------------------- ### Retry Throttling Configuration Source: https://grpc.io/docs/guides/request-hedging Configure retry throttling to prevent server overload when using hedging. This limits the number of concurrent hedged requests based on available tokens. ```json "retryThrottling": { "maxTokens": 10, "tokenRatio": 0.1 } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.