Esempio n. 1
0
        public static async Task RunCustomMetadataAsync(TestService.TestServiceClient client)
        {
            Console.WriteLine("running custom_metadata");
            {
                // step 1: test unary call
                var request = new SimpleRequest
                {
                    ResponseSize = 314159,
                    Payload      = CreateZerosPayload(271828)
                };

                var call = client.UnaryCallAsync(request, headers: CreateTestMetadata());
                await call.ResponseAsync;

                var responseHeaders  = await call.ResponseHeadersAsync;
                var responseTrailers = call.GetTrailers();

                Assert.AreEqual("test_initial_metadata_value", responseHeaders.First((entry) => entry.Key == "x-grpc-test-echo-initial").Value);
                CollectionAssert.AreEqual(new byte[] { 0xab, 0xab, 0xab }, responseTrailers.First((entry) => entry.Key == "x-grpc-test-echo-trailing-bin").ValueBytes);
            }

            {
                // step 2: test full duplex call
                var request = new StreamingOutputCallRequest
                {
                    ResponseParameters = { new ResponseParameters {
                                               Size = 31415
                                           } },
                    Payload = CreateZerosPayload(27182)
                };

                var call = client.FullDuplexCall(headers: CreateTestMetadata());

                await call.RequestStream.WriteAsync(request);

                await call.RequestStream.CompleteAsync();

                await call.ResponseStream.ToListAsync();

                var responseHeaders  = await call.ResponseHeadersAsync;
                var responseTrailers = call.GetTrailers();

                Assert.AreEqual("test_initial_metadata_value", responseHeaders.First((entry) => entry.Key == "x-grpc-test-echo-initial").Value);
                CollectionAssert.AreEqual(new byte[] { 0xab, 0xab, 0xab }, responseTrailers.First((entry) => entry.Key == "x-grpc-test-echo-trailing-bin").ValueBytes);
            }

            Console.WriteLine("Passed!");
        }
Esempio n. 2
0
        async Task RunBodyAsync(TestService.TestServiceClient client)
        {
            Logger.Info("Starting stress test client thread.");
            while (!finishedTokenSource.Token.IsCancellationRequested)
            {
                var testCase = testCaseGenerator.GetNext();

                var stopwatch = Stopwatch.StartNew();

                await RunTestCaseAsync(client, testCase);

                stopwatch.Stop();
                histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
            }
            Logger.Info("Stress test client thread finished.");
        }
Esempio n. 3
0
        public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client, string oauthScope)
        {
            Console.WriteLine("running per_rpc_creds");
            ITokenAccess googleCredential = await GoogleCredential.GetApplicationDefaultAsync();

            var credentials = googleCredential.ToCallCredentials();
            var request     = new SimpleRequest
            {
                FillUsername = true,
            };

            var response = client.UnaryCall(request, new CallOptions(credentials: credentials));

            Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username);
            Console.WriteLine("Passed!");
        }
Esempio n. 4
0
        public void MetadataCredentials_InterceptorThrows()
        {
            var callCredentials = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) =>
            {
                throw new Exception("Auth interceptor throws");
            }));
            var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(), callCredentials);

            channel = new Channel(Host, server.Ports.Single().BoundPort, channelCredentials, options);
            client  = new TestService.TestServiceClient(channel);

            var ex = Assert.Throws <RpcException>(() => client.UnaryCall(new SimpleRequest {
            }));

            Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
        }
        public void MetadataCredentials_InterceptorLeavesMetadataEmpty()
        {
            serviceImpl.UnaryCallHandler = (req, context) =>
            {
                var authHeaderCount = context.RequestHeaders.Count((entry) => entry.Key == "authorization");
                Assert.AreEqual(0, authHeaderCount);
                return(Task.FromResult(new SimpleResponse()));
            };
            var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(),
                                                               CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => TaskUtils.CompletedTask)));

            channel = new Channel(Host, server.Ports.Single().BoundPort, channelCredentials, options);
            client  = new TestService.TestServiceClient(channel);
            client.UnaryCall(new SimpleRequest {
            });
        }
Esempio n. 6
0
        public static async Task RunStatusCodeAndMessageAsync(TestService.TestServiceClient client)
        {
            Console.WriteLine("running status_code_and_message");
            var echoStatus = new EchoStatus
            {
                Code    = 2,
                Message = "test status message"
            };

            {
                // step 1: test unary call
                var request = new SimpleRequest {
                    ResponseStatus = echoStatus
                };

                var e = Assert.Throws <RpcException>(() => client.UnaryCall(request));
                Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode);
                Assert.AreEqual(echoStatus.Message, e.Status.Detail);
            }

            {
                // step 2: test full duplex call
                var request = new StreamingOutputCallRequest {
                    ResponseStatus = echoStatus
                };

                var call = client.FullDuplexCall();
                await call.RequestStream.WriteAsync(request);

                await call.RequestStream.CompleteAsync();

                try
                {
                    // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock.
                    await call.ResponseStream.ToListAsync();

                    Assert.Fail();
                }
                catch (RpcException e)
                {
                    Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode);
                    Assert.AreEqual(echoStatus.Message, e.Status.Detail);
                }
            }

            Console.WriteLine("Passed!");
        }
Esempio n. 7
0
        public static async Task RunCancelAfterBeginAsync(TestService.TestServiceClient client)
        {
            Console.WriteLine("running cancel_after_begin");

            var cts = new CancellationTokenSource();

            using (var call = client.StreamingInputCall(cancellationToken: cts.Token))
            {
                // TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it.
                await Task.Delay(1000);

                cts.Cancel();

                var ex = Assert.ThrowsAsync <RpcException>(async() => await call.ResponseAsync);
                Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode);
            }
            Console.WriteLine("Passed!");
        }
Esempio n. 8
0
        public void Init()
        {
            server = new Server
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports    = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } }
            };
            server.Start();

            var options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };
            int port = server.Ports.Single().BoundPort;

            channel = new Channel(Host, port, TestCredentials.CreateSslCredentials(), options);
            client  = TestService.NewClient(channel);
        }
Esempio n. 9
0
        public static void RunJwtTokenCreds(TestService.TestServiceClient client)
        {
            Console.WriteLine("running jwt_token_creds");

            var request = new SimpleRequest
            {
                ResponseSize = 314159,
                Payload      = CreateZerosPayload(271828),
                FillUsername = true,
            };

            // not setting credentials here because they were set on channel already
            var response = client.UnaryCall(request);

            Assert.AreEqual(314159, response.Payload.Body.Length);
            Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username);
            Console.WriteLine("Passed!");
        }
Esempio n. 10
0
        public static void RunClientCompressedUnary(TestService.TestServiceClient client)
        {
            Console.WriteLine("running client_compressed_unary");
            var probeRequest = new SimpleRequest
            {
                ExpectCompressed = new BoolValue
                {
                    Value = true  // lie about compression
                },
                ResponseSize = 314159,
                Payload      = CreateZerosPayload(271828)
            };
            var e = Assert.Throws <RpcException>(() => client.UnaryCall(probeRequest, CreateClientCompressionMetadata(false)));

            Assert.AreEqual(StatusCode.InvalidArgument, e.Status.StatusCode);

            var compressedRequest = new SimpleRequest
            {
                ExpectCompressed = new BoolValue
                {
                    Value = true
                },
                ResponseSize = 314159,
                Payload      = CreateZerosPayload(271828)
            };
            var response1 = client.UnaryCall(compressedRequest, CreateClientCompressionMetadata(true));

            Assert.AreEqual(314159, response1.Payload.Body.Length);

            var uncompressedRequest = new SimpleRequest
            {
                ExpectCompressed = new BoolValue
                {
                    Value = false
                },
                ResponseSize = 314159,
                Payload      = CreateZerosPayload(271828)
            };
            var response2 = client.UnaryCall(uncompressedRequest, CreateClientCompressionMetadata(false));

            Assert.AreEqual(314159, response2.Payload.Body.Length);

            Console.WriteLine("Passed!");
        }
        public void Init()
        {
            // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755
            server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) })
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports    = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } }
            };
            server.Start();

            var options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };
            int port = server.Ports.Single().BoundPort;

            channel = new Channel(Host, port, TestCredentials.CreateSslCredentials(), options);
            client  = new TestService.TestServiceClient(channel);
        }
Esempio n. 12
0
        public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client)
        {
            Console.WriteLine("running oauth2_auth_token");
            ITokenAccess credential  = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { AuthScope });
            string       oauth2Token = await credential.GetAccessTokenForRequestAsync();

            client.HeaderInterceptor = OAuth2Interceptors.FromAccessToken(oauth2Token);

            var request = SimpleRequest.CreateBuilder()
                          .SetFillUsername(true)
                          .SetFillOauthScope(true)
                          .Build();

            var response = client.UnaryCall(request);

            Assert.AreEqual(AuthScopeResponse, response.OauthScope);
            Assert.AreEqual(ServiceAccountUser, response.Username);
            Console.WriteLine("Passed!");
        }
Esempio n. 13
0
        public static async Task RunClientStreamingAsync(TestService.TestServiceClient client)
        {
            Console.WriteLine("running client_streaming");

            var bodySizes = new List <int> {
                27182, 8, 1828, 45904
            }.Select((size) => new StreamingInputCallRequest {
                Payload = CreateZerosPayload(size)
            });

            using (var call = client.StreamingInputCall())
            {
                await call.RequestStream.WriteAllAsync(bodySizes);

                var response = await call.ResponseAsync;
                Assert.AreEqual(74922, response.AggregatedPayloadSize);
            }
            Console.WriteLine("Passed!");
        }
Esempio n. 14
0
        public static void Main(string[] args)
        {
            Channel channel = new Channel("127.0.0.1:50501", ChannelCredentials.Insecure);

            var client = new TestService.TestServiceClient(channel);

            var reply = client.GetTime(new Request {
                Body = "getting time", Type = "time_request"
            });
            var reply2 = client.SaySomething(new Request {
                Body = "I am saying something", Type = "say_something"
            });

            Console.WriteLine("Greeting: " + reply.Body);

            channel.ShutdownAsync().Wait();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Esempio n. 15
0
        async Task Run()
        {
            var metricsServer = new Server()
            {
                Services = { MetricsService.BindService(new MetricsServiceImpl(histogram)) },
                Ports    = { { "[::]", options.MetricsPort, ServerCredentials.Insecure } }
            };

            metricsServer.Start();

            if (options.TestDurationSecs >= 0)
            {
                finishedTokenSource.CancelAfter(TimeSpan.FromSeconds(options.TestDurationSecs));
            }

            var tasks    = new List <Task>();
            var channels = new List <Channel>();

            foreach (var serverAddress in serverAddresses)
            {
                for (int i = 0; i < options.NumChannelsPerServer; i++)
                {
                    var channel = new Channel(serverAddress, ChannelCredentials.Insecure);
                    channels.Add(channel);
                    for (int j = 0; j < options.NumStubsPerChannel; j++)
                    {
                        var client = new TestService.TestServiceClient(channel);
                        var task   = Task.Factory.StartNew(() => RunBodyAsync(client).GetAwaiter().GetResult(),
                                                           TaskCreationOptions.LongRunning);
                        tasks.Add(task);
                    }
                }
            }
            await Task.WhenAll(tasks);

            foreach (var channel in channels)
            {
                await channel.ShutdownAsync();
            }

            await metricsServer.ShutdownAsync();
        }
Esempio n. 16
0
        public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client, string oauthScope)
        {
            Console.WriteLine("running oauth2_auth_token");
            ITokenAccess credential  = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope });
            string       oauth2Token = await credential.GetAccessTokenForRequestAsync();

            var credentials = GoogleGrpcCredentials.FromAccessToken(oauth2Token);
            var request     = new SimpleRequest
            {
                FillUsername   = true,
                FillOauthScope = true
            };

            var response = client.UnaryCall(request, new CallOptions(credentials: credentials));

            Assert.False(string.IsNullOrEmpty(response.OauthScope));
            Assert.True(oauthScope.Contains(response.OauthScope));
            Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username);
            Console.WriteLine("Passed!");
        }
Esempio n. 17
0
        private async Task Run()
        {
            var credentials = await CreateCredentialsAsync();

            List <ChannelOption> channelOptions = null;

            if (!string.IsNullOrEmpty(options.ServerHostOverride))
            {
                channelOptions = new List <ChannelOption>
                {
                    new ChannelOption(ChannelOptions.SslTargetNameOverride, options.ServerHostOverride)
                };
            }
            var channel = new Channel(options.ServerHost, options.ServerPort, credentials, channelOptions);

            TestService.TestServiceClient client = new TestService.TestServiceClient(channel);
            await RunTestCaseAsync(client, options);

            await channel.ShutdownAsync();
        }
        public async Task UnhandledException_AvailableThroughLastExceptionFilter()
        {
            var expectedException = new Exception("test");

            var handler = new GrpcRequestHandler <TestRequest, TestResponse>
            {
                Method  = TestService.Descriptor.FindMethodByName("TestThrow"),
                Handler = (req, ctx) => throw expectedException
            };

            GrpcHandlers = new[] { handler };
            Build();

            var request = new TestRequest();
            var client  = new TestService.TestServiceClient(Channel);

            _ = await Assert.ThrowsAsync <RpcException>(async() => await client.TestThrowAsync(request));

            Assert.Same(expectedException, SentryGrpcTestInterceptor.LastException);
        }
    }
Esempio n. 19
0
        public static void RunComputeEngineCreds(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope)
        {
            Console.WriteLine("running compute_engine_creds");

            var request = new SimpleRequest
            {
                ResponseSize   = 314159,
                Payload        = CreateZerosPayload(271828),
                FillUsername   = true,
                FillOauthScope = true
            };

            // not setting credentials here because they were set on channel already
            var response = client.UnaryCall(request);

            Assert.AreEqual(314159, response.Payload.Body.Length);
            Assert.False(string.IsNullOrEmpty(response.OauthScope));
            Assert.True(oauthScope.Contains(response.OauthScope));
            Assert.AreEqual(defaultServiceAccount, response.Username);
            Console.WriteLine("Passed!");
        }
Esempio n. 20
0
        public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client, string oauthScope)
        {
#if !NETCOREAPP1_0
            Console.WriteLine("running per_rpc_creds");
            ITokenAccess googleCredential = await GoogleCredential.GetApplicationDefaultAsync();

            var credentials = googleCredential.ToCallCredentials();
            var request     = new SimpleRequest
            {
                FillUsername = true,
            };

            var response = client.UnaryCall(request, new CallOptions(credentials: credentials));

            Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username);
            Console.WriteLine("Passed!");
#else
            // TODO(jtattermusch): implement this
            throw new NotImplementedException("Not supported on CoreCLR yet");
#endif
        }
Esempio n. 21
0
        private static async Task ServerStreamingAsync(TestService.TestServiceClient client)
        {
            var cts = new CancellationTokenSource();

            cts.CancelAfter(TimeSpan.FromSeconds(4));
            using var reply = client.SayHellos(new HelloRequest { Name = "mostafa laoy" });
            try
            {
                while (await reply.ResponseStream.MoveNext())
                {
                    Console.WriteLine(reply.ResponseStream.Current.Message);
                }
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("End Server Stream");
            }
            catch (RpcException ex) when(ex.StatusCode == StatusCode.Cancelled)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Stream cancelled.");
            }
        }
Esempio n. 22
0
        private void Run()
        {
            GrpcEnvironment.Initialize();

            Credentials credentials = null;

            if (options.useTls)
            {
                credentials = TestCredentials.CreateTestClientCredentials(options.useTestCa);
            }

            List <ChannelOption> channelOptions = null;

            if (!string.IsNullOrEmpty(options.serverHostOverride))
            {
                channelOptions = new List <ChannelOption>
                {
                    new ChannelOption(ChannelOptions.SslTargetNameOverride, options.serverHostOverride)
                };
            }

            using (Channel channel = new Channel(options.serverHost, options.serverPort.Value, credentials, channelOptions))
            {
                var stubConfig = StubConfiguration.Default;
                if (options.testCase == "service_account_creds" || options.testCase == "compute_engine_creds")
                {
                    var credential = GoogleCredential.GetApplicationDefault();
                    if (credential.IsCreateScopedRequired)
                    {
                        credential = credential.CreateScoped(new[] { AuthScope });
                    }
                    stubConfig = new StubConfiguration(OAuth2InterceptorFactory.Create(credential));
                }

                TestService.ITestServiceClient client = new TestService.TestServiceClient(channel, stubConfig);
                RunTestCase(options.testCase, client);
            }

            GrpcEnvironment.Shutdown();
        }
Esempio n. 23
0
        public static async Task RunTimeoutOnSleepingServerAsync(TestService.TestServiceClient client)
        {
            Console.WriteLine("running timeout_on_sleeping_server");

            var deadline = DateTime.UtcNow.AddMilliseconds(1);

            using (var call = client.FullDuplexCall(deadline: deadline))
            {
                try
                {
                    await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { Payload = CreateZerosPayload(27182) });
                }
                catch (InvalidOperationException)
                {
                    // Deadline was reached before write has started. Eat the exception and continue.
                }

                var ex = Assert.ThrowsAsync <RpcException>(async() => await call.ResponseStream.MoveNext());
                Assert.AreEqual(StatusCode.DeadlineExceeded, ex.Status.StatusCode);
            }
            Console.WriteLine("Passed!");
        }
Esempio n. 24
0
        static async Task Main(string[] args)
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            using GrpcChannel channel = GrpcChannel.ForAddress("http://127.0.0.1:50051");
            TestService.TestServiceClient client = new TestService.TestServiceClient(channel);

            TabIndex opt = TabIndex.Home;

            try
            {
                while (Enum.TryParse(Console.ReadLine(), true, out opt))
                {
                    await client.SetTabAsync(new ChangeTab()
                    {
                        Tab = opt
                    });
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Esempio n. 25
0
        public static async Task RunServerStreamingAsync(TestService.TestServiceClient client)
        {
            Console.WriteLine("running server_streaming");

            var bodySizes = new List <int> {
                31415, 9, 2653, 58979
            };

            var request = new StreamingOutputCallRequest
            {
                ResponseParameters = { bodySizes.Select((size) => new ResponseParameters {
                        Size = size
                    }) }
            };

            using (var call = client.StreamingOutputCall(request))
            {
                var responseList = await call.ResponseStream.ToListAsync();

                CollectionAssert.AreEqual(bodySizes, responseList.Select((item) => item.Payload.Body.Length));
            }
            Console.WriteLine("Passed!");
        }
        public async Task MetadataCredentials_ComposedPerCall()
        {
            channel = new Channel(Host, server.Ports.Single().BoundPort, TestCredentials.CreateSslCredentials(), options);
            var client = new TestService.TestServiceClient(channel);
            var first  = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                metadata.Add("first_authorization", "FIRST_SECRET_TOKEN");
                return(TaskUtils.CompletedTask);
            }));
            var second = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                metadata.Add("second_authorization", "SECOND_SECRET_TOKEN");
                return(TaskUtils.CompletedTask);
            }));
            var third = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                metadata.Add("third_authorization", "THIRD_SECRET_TOKEN");
                return(TaskUtils.CompletedTask);
            }));
            var call = client.StreamingOutputCall(new StreamingOutputCallRequest {
            },
                                                  new CallOptions(credentials: CallCredentials.Compose(first, second, third)));

            Assert.IsTrue(await call.ResponseStream.MoveNext());
            Assert.IsFalse(await call.ResponseStream.MoveNext());
        }
Esempio n. 27
0
        public static async Task HandleServerStreamingCallAsync(TestService.TestServiceClient client)
        {
            var inputKey = Console.ReadLine();
            var input    = new EchoInput()
            {
                Input = inputKey
            };

            var tokenSource = new CancellationTokenSource();

            if (inputKey == "Q")
            {
                tokenSource.Cancel();
            }

            var resStream = client.GetEchoStream(input, deadline: DateTime.UtcNow.AddSeconds(10), cancellationToken: tokenSource.Token);

            while (await resStream.ResponseStream.MoveNext())
            {
                Console.WriteLine("Get echo from stream: " + resStream.ResponseStream.Current.Output.Trim());
                Console.WriteLine("Get echo time: " + resStream.ResponseStream.Current.TimeStamp.ToDateTime().ToLocalTime());
            }
        }
Esempio n. 28
0
        public void Init()
        {
            // TODO(https://github.com/grpc/grpc/issues/14963): on linux, setting
            // these environment variables might not actually have any affect.
            // This is OK because we only really care about running this test on
            // Windows, however, a fix made for $14963 should be applied here.
            Environment.SetEnvironmentVariable("GRPC_TRACE", "all");
            Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG");
            newLogger = new SocketUsingLogger(GrpcEnvironment.Logger);
            GrpcEnvironment.SetLogger(newLogger);
            // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755
            server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) })
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports    = { { "[::1]", ServerPort.PickUnused, ServerCredentials.Insecure } }
            };
            server.Start();

            int port = server.Ports.Single().BoundPort;

            channel = new Channel("loopback6.unittest.grpc.io", port, ChannelCredentials.Insecure);
            client  = new TestService.TestServiceClient(channel);
        }
        public void MetadataCredentials_PerCall()
        {
            serviceImpl.UnaryCallHandler = (req, context) =>
            {
                var authToken = context.RequestHeaders.First((entry) => entry.Key == "authorization").Value;
                Assert.AreEqual("SECRET_TOKEN", authToken);
                return(Task.FromResult(new SimpleResponse()));
            };

            var asyncAuthInterceptor = new AsyncAuthInterceptor(async(context, metadata) =>
            {
                await Task.Delay(100).ConfigureAwait(false);  // make sure the operation is asynchronous.
                metadata.Add("authorization", "SECRET_TOKEN");
            });

            channel = new Channel(Host, server.Ports.Single().BoundPort, TestCredentials.CreateSslCredentials(), options);
            client  = new TestService.TestServiceClient(channel);

            var callCredentials = CallCredentials.FromInterceptor(asyncAuthInterceptor);

            client.UnaryCall(new SimpleRequest {
            }, new CallOptions(credentials: callCredentials));
        }
Esempio n. 30
0
        public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client)
        {
            Console.WriteLine("running per_rpc_creds");

            ITokenAccess credential  = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { AuthScope });
            string       oauth2Token = await credential.GetAccessTokenForRequestAsync();

            var headerInterceptor = AuthInterceptors.FromAccessToken(oauth2Token);

            var request = SimpleRequest.CreateBuilder()
                          .SetFillUsername(true)
                          .SetFillOauthScope(true)
                          .Build();

            var headers = new Metadata();

            headerInterceptor(null, "", headers);
            var response = client.UnaryCall(request, headers: headers);

            Assert.AreEqual(AuthScopeResponse, response.OauthScope);
            Assert.AreEqual(ServiceAccountUser, response.Username);
            Console.WriteLine("Passed!");
        }