protected GrpcChannel CreateAuthenticatedChannel(string grpcAddress)
    {
        CallCredentials credentials = CallCredentials.FromInterceptor((context, metadata) =>
        {
            if (!string.IsNullOrEmpty(Token))
            {
                metadata.Add("Authorization", $"Bearer {Token}");
            }

            return(Task.CompletedTask);
        });

        GrpcWebHandler handler = new(GrpcWebMode.GrpcWeb,
                                     new HttpClientHandler
        {
            ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
        });

        handler.HttpVersion = new Version(1, 1);

        _channel = GrpcChannel.ForAddress(grpcAddress,
                                          new GrpcChannelOptions
        {
            Credentials = ChannelCredentials.Create(new SslCredentials(), credentials),
            HttpClient  = new HttpClient(handler)
        });

        return(_channel);
    }
Esempio n. 2
0
        private static CallCredentials GetJwtCredentials(string token) =>
        CallCredentials.FromInterceptor((_, metadata) =>
        {
            metadata.AddJwt(token);

            return(Task.CompletedTask);
        });
        /// <summary>
        /// Create authenticated channel to gRpc Service Client
        /// </summary>
        /// <param name="address">Url address</param>
        /// <param name="token">Token authentication</param>
        private GrpcChannel CreateAuthenticatedChannel(string address, string token)
        {
            CallCredentials credentials = CallCredentials.FromInterceptor((context, metadata) =>
            {
                if (!string.IsNullOrWhiteSpace(token))
                {
                    metadata.Add("Authorization", $"Bearer {token}");
                }
                return(Task.CompletedTask);
            });


            GrpcChannel channel;

            if (_isProduction)
            {
                channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions
                {
                    Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)
                });
            }
            else
            {
                channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions
                {
                    HttpClient = new HttpClient(new HttpClientHandler
                    {
                        ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                    }),
                    Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)
                });
            }
            return(channel);
        }
Esempio n. 4
0
        private static async Task ServerStream()
        {
            var credentials = CallCredentials.FromInterceptor((c, m) => {
                m.Add("Authorization",
                      "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InRlc3QxIiwibmJmIjoxNTgxOTYyNzI0LCJleHAiOjE1ODE5NjYzMjQsImlhdCI6MTU4MTk2MjcyNH0.VvYln0PgZQrFwBTx0Ik3TGGI43DxdVVxzHAXma-K5P0");
                return(Task.CompletedTask);
            });

            var channel = GrpcChannel.ForAddress("https://localhost:5001/",
                                                 new GrpcChannelOptions
            {
                Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)
            });

            var client = new GrpcClientCount.ClientCountProvider.ClientCountProviderClient(channel);

            var token = new CancellationTokenSource(TimeSpan.FromSeconds(5));

            using var population = client.GetClientCount(
                      new Empty(),
                      cancellationToken: token.Token);
            try
            {
                await foreach (var item in population.ResponseStream.ReadAllAsync(token.Token))
                {
                    Console.WriteLine(item.Count);
                }
            }
            catch (RpcException exc)
            {
                Console.WriteLine(exc.Message);
            }
        }
        public async Task AsyncUnaryCall_AuthInterceptorSuccess_ResponseHeadersPopulated()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                var reply = new HelloReply {
                    Message = "Hello world"
                };
                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();
                var response      = ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent);
                response.Headers.Add("custom", "ABC");
                return(response);
            });
            var credentialsSyncPoint = new SyncPoint(runContinuationsAsynchronously: true);
            var credentials          = CallCredentials.FromInterceptor(async(context, metadata) =>
            {
                await credentialsSyncPoint.WaitToContinue();
                metadata.Add("Authorization", $"Bearer TEST");
            });

            var invoker = HttpClientCallInvokerFactory.Create(httpClient, configure: options => options.Credentials = ChannelCredentials.Create(new SslCredentials(), credentials));

            // Act
            var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest());
            var responseHeadersTask = call.ResponseHeadersAsync;

            await credentialsSyncPoint.WaitForSyncPoint().DefaultTimeout();

            credentialsSyncPoint.Continue();

            var responseHeaders = await responseHeadersTask.DefaultTimeout();

            // Assert
            Assert.AreEqual("ABC", responseHeaders.GetValue("custom"));
        }
        private ChannelBase CreateSecureChannel()
        {
            var getEC2TagOption = configuration.GetEC2TagOptionFromEC2TagsSection();
            var environmentTag  = getEC2TagOption.Environment;
            var customerTag     = getEC2TagOption.Customer;

            var jwtBearerTokenSymetricSecurityKey = refinitivTickPriceHistoryApiConfig.RefinitivTickPriceHistoryApiJwtBearerTokenSymetricSecurityKey;

            var credentials = CallCredentials.FromInterceptor((context, metadata) =>
            {
                var jwtToken = new JwtToken()
                               .SetExpires(DateTime.UtcNow.AddMinutes(2))
                               .SetIssuer(environmentTag, customerTag, PermissionScopeTypeConstants.TickPriceHistory)
                               .SetAudience(environmentTag, customerTag, PermissionScopeTypeConstants.TickPriceHistory);

                var bearerToken = jwtTokenService.Generate(jwtToken, jwtBearerTokenSymetricSecurityKey);

                metadata.Add("Authorization", $"Bearer {bearerToken}");
                return(Task.CompletedTask);
            });


            var channelCredentials = ChannelCredentials.Create(new SslCredentials(), credentials);
            var grpcChannelOptions = new GrpcChannelOptions
            {
                //HttpClient = httpClient,
                // LoggerFactory = logFactory,
                Credentials = channelCredentials
            };

            var channel = GrpcChannel.ForAddress(refinitivTickPriceHistoryApiConfig.RefinitivTickPriceHistoryApiAddress, grpcChannelOptions);

            return(channel);
        }
        public async Task CallCredentialsWithHttps_WhenAsyncAuthInterceptorThrow_ShouldThrow()
        {
            // Arrange
            var services = new ServiceCollection();

            services.AddNUnitLogger();
            var loggerFactory = services.BuildServiceProvider().GetRequiredService <ILoggerFactory>();

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                var reply = new HelloReply {
                    Message = "Hello world"
                };
                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();
                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient, loggerFactory);

            // Act
            var expectedException = new Exception("Some AsyncAuthInterceptor Exception");

            var callCredentials = CallCredentials.FromInterceptor((context, metadata) =>
            {
                return(Task.FromException(expectedException));
            });

            var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(credentials: callCredentials), new HelloRequest());
            var ex   = await ExceptionAssert.ThrowsAsync <RpcException>(() => call.ResponseAsync).DefaultTimeout();

            // Assert
            Assert.AreSame(expectedException, ex.Status.DebugException);
        }
        public async Task CallCredentials_AuthContextPopulated(string target, string expectedServiceUrl)
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                var reply = new HelloReply {
                    Message = "Hello world"
                };
                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();
                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            }, new Uri(target));
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            string?serviceUrl      = null;
            string?methodName      = null;
            var    callCredentials = CallCredentials.FromInterceptor((context, metadata) =>
            {
                serviceUrl = context.ServiceUrl;
                methodName = context.MethodName;
                return(Task.CompletedTask);
            });
            var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(credentials: callCredentials), new HelloRequest());
            await call.ResponseAsync.DefaultTimeout();

            // Assert
            Assert.AreEqual(expectedServiceUrl, serviceUrl);
            Assert.AreEqual("MethodName", ClientTestHelpers.ServiceMethod.Name);
        }
Esempio n. 9
0
        static async Task Main(string[] args)
        {
            var token = await Authenticate("Alice");

            var channel = GrpcChannel.ForAddress(ServerAddress, new GrpcChannelOptions
            {
                Credentials = ChannelCredentials.Create(new SslCredentials(), CallCredentials.FromInterceptor((context, metadata) =>
                {
                    metadata.Add("Authorization", $"Bearer {token}");
                    return(Task.CompletedTask);
                }))
            });
            var portfolios = new Portfolios.PortfoliosClient(channel);

            try
            {
                var request = new GetRequest
                {
                    TraderId    = "68CB16F7-42BD-4330-A191-FA5904D2E5A0",
                    PortfolioId = 42
                };
                var response = await portfolios.GetAsync(request);

                Console.WriteLine($"Portfolio contains {response.Portfolio.Items.Count} items.");
            }
            catch (RpcException e)
            {
                if (e.StatusCode == StatusCode.PermissionDenied)
                {
                    Console.WriteLine("Permission denied.");
                }
            }
        }
        public void MetadataCredentials_BothChannelAndPerCall()
        {
            serviceImpl.UnaryCallHandler = (req, context) =>
            {
                var firstAuth = context.RequestHeaders.First((entry) => entry.Key == "first_authorization").Value;
                Assert.AreEqual("FIRST_SECRET_TOKEN", firstAuth);
                var secondAuth = context.RequestHeaders.First((entry) => entry.Key == "second_authorization").Value;
                Assert.AreEqual("SECOND_SECRET_TOKEN", secondAuth);
                // both values of "duplicate_authorization" are sent
                Assert.AreEqual("value1", context.RequestHeaders.First((entry) => entry.Key == "duplicate_authorization").Value);
                Assert.AreEqual("value2", context.RequestHeaders.Last((entry) => entry.Key == "duplicate_authorization").Value);
                return(Task.FromResult(new SimpleResponse()));
            };

            var channelCallCredentials = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                metadata.Add("first_authorization", "FIRST_SECRET_TOKEN");
                metadata.Add("duplicate_authorization", "value1");
                return(TaskUtils.CompletedTask);
            }));
            var perCallCredentials = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                metadata.Add("second_authorization", "SECOND_SECRET_TOKEN");
                metadata.Add("duplicate_authorization", "value2");
                return(TaskUtils.CompletedTask);
            }));

            var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(), channelCallCredentials);

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

            client.UnaryCall(new SimpleRequest {
            }, new CallOptions(credentials: perCallCredentials));
        }
        public async Task MetadataCredentials_Composed()
        {
            var first = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                // Attempt to exercise the case where async callback is inlineable/synchronously-runnable.
                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 channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(),
                                                               CallCredentials.Compose(first, second, third));

            channel = new Channel(Host, server.Ports.Single().BoundPort, channelCredentials, options);
            var client = new TestService.TestServiceClient(channel);
            var call   = client.StreamingOutputCall(new StreamingOutputCallRequest {
            });

            Assert.IsTrue(await call.ResponseStream.MoveNext());
            Assert.IsFalse(await call.ResponseStream.MoveNext());
        }
        public ScoringClient(string host, int port, bool useSsl = false, string authKey = null, string serviceName = null)
        {
            ChannelCredentials baseCreds, creds;

            baseCreds = useSsl ? new SslCredentials() : ChannelCredentials.Insecure;
            if (authKey != null && useSsl)
            {
                creds = ChannelCredentials.Create(baseCreds, CallCredentials.FromInterceptor(
                                                      async(context, metadata) =>
                {
                    metadata.Add(new Metadata.Entry("authorization", authKey));
                    await Task.CompletedTask;
                }));
            }
            else
            {
                creds = baseCreds;
            }
            var channel     = new Channel(host, port, creds);
            var callInvoker = channel.Intercept(
                metadata =>
            {
                metadata.Add(
                    new Metadata.Entry("x-ms-aml-grpc-service-route", $"/api/v1/service/{serviceName}"));
                return(metadata);
            });

            _client = new PredictionServiceClientWrapper(new PredictionService.PredictionServiceClient(callInvoker));
        }
        static ChannelCredentials CreateCredentials(bool mutualTls, bool useJwt)
        {
            var certsPath = Environment.GetEnvironmentVariable("CERTS_PATH");

            var caRoots = File.ReadAllText(Path.Combine(certsPath, "ca.pem"));
            ChannelCredentials channelCredentials;

            if (!mutualTls)
            {
                channelCredentials = new SslCredentials(caRoots);
            }
            else
            {
                var keyCertPair = new KeyCertificatePair(
                    File.ReadAllText(Path.Combine(certsPath, "client.pem")),
                    File.ReadAllText(Path.Combine(certsPath, "client.key")));
                channelCredentials = new SslCredentials(caRoots, keyCertPair);
            }

            if (useJwt)
            {
                var authInterceptor = new AsyncAuthInterceptor(async(context, metadata) =>
                {
                    metadata.Add(
                        new Metadata.Entry("authorization", "Bearer " + GenerateJwt()));
                });

                var metadataCredentials = CallCredentials.FromInterceptor(authInterceptor);
                channelCredentials = ChannelCredentials.Create(channelCredentials, metadataCredentials);
            }
            return(channelCredentials);
        }
Esempio n. 14
0
        public async Task ConnectAsync(RobotConnectionInfo connectionInfo)
        {
            if (Client == null)
            {
                //create channel
                var ssl         = new SslCredentials(connectionInfo.Certificate);
                var interceptor = new AsyncAuthInterceptor((context, metadata) =>
                {
                    metadata.Add("authorization", $"Bearer {connectionInfo.Token}");
                    return(Task.CompletedTask);
                });
                var cred = ChannelCredentials.Create(ssl, CallCredentials.FromInterceptor(interceptor));
                _channel = new Channel(connectionInfo.IpAddress, 443, cred, new ChannelOption[] { new ChannelOption("grpc.ssl_target_name_override", connectionInfo.RobotName) });

                //connect to client
                try
                {
                    await _channel.ConnectAsync(DateTime.UtcNow.AddSeconds(10));
                }
                catch (TaskCanceledException ex)
                {
                    throw new VectorConnectionException("could not connect to Vector.  insure IP address is correct and that Vector is turned on", ex);
                }

                //create client
                Client      = new ExternalInterfaceClient(_channel);
                IsConnected = true;
            }
        }
        public async Task CallCredentialsWithHttps_MetadataOnRequest()
        {
            // Arrange
            string?authorizationValue = null;
            var    httpClient         = ClientTestHelpers.CreateTestClient(async request =>
            {
                authorizationValue = request.Headers.GetValues("authorization").Single();

                var reply = new HelloReply {
                    Message = "Hello world"
                };
                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();
                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            var callCredentials = CallCredentials.FromInterceptor(async(context, metadata) =>
            {
                // The operation is asynchronous to ensure delegate is awaited
                await Task.Delay(50);
                metadata.Add("authorization", "SECRET_TOKEN");
            });
            var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(credentials: callCredentials), new HelloRequest());
            await call.ResponseAsync.DefaultTimeout();

            // Assert
            Assert.AreEqual("SECRET_TOKEN", authorizationValue);
        }
Esempio n. 16
0
        private static GrpcChannel CreateAuthenticatedChannel(string address)
        {
            var credentials = CallCredentials.FromInterceptor((context, metadata) =>
            {
                if (!string.IsNullOrEmpty(_token))
                {
                    metadata.Add("Authorization", $"Bearer {_token}");
                }
                return(Task.CompletedTask);
            });

            // SslCredentials is used here because this channel is using TLS.

            // Channels that aren't using TLS should use ChannelCredentials.Insecure instead.
            var httpHandler = new HttpClientHandler();

            httpHandler.ServerCertificateCustomValidationCallback =
                HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;


            var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions
            {
                Credentials = ChannelCredentials.Create(new SslCredentials(), credentials),
                HttpHandler = httpHandler
            });

            return(channel);
        }
        private static GrpcChannel CreateGrpcChannel(IServiceProvider sp)
        {
            var navigationManager = sp.GetRequiredService <NavigationManager>();
            var options           = sp.GetRequiredService <IOptions <ElsaDashboardWebAssemblyOptions> >();
            var backendUrl        = options.Value.BackendUrl?.ToString() ?? navigationManager.BaseUri;
            var httpClient        = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));

            //var tokenManager = sp.GetRequiredService<ITokenManager>();

            var credentials = CallCredentials.FromInterceptor(
                (context, metadata) =>
            {
                //var accessToken = await tokenManager.GetAccessTokenAsync();
                var accessToken = "";

                if (!string.IsNullOrEmpty(accessToken))
                {
                    metadata.Add("Authorization", $"Bearer {accessToken}");
                }

                return(Task.CompletedTask);
            });

            var channel = GrpcChannel.ForAddress(
                backendUrl,
                new GrpcChannelOptions
            {
                HttpClient  = httpClient,
                Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)
            });

            return(channel);
        }
Esempio n. 18
0
        private static async Task ClientStream()
        {
            var credentials = CallCredentials.FromInterceptor((c, m) => {
                m.Add("Authorization",
                      "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InRlc3QxIiwibmJmIjoxNTgxOTYyNzI0LCJleHAiOjE1ODE5NjYzMjQsImlhdCI6MTU4MTk2MjcyNH0.VvYln0PgZQrFwBTx0Ik3TGGI43DxdVVxzHAXma-K5P0");
                return(Task.CompletedTask);
            });

            var channel = GrpcChannel.ForAddress("https://localhost:5001/",
                                                 new GrpcChannelOptions
            {
                Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)
            });

            var client = new GrpcPopulation.PopulationProvider.PopulationProviderClient(channel);

            using var populationRequest = client.GetPopulation();

            foreach (var state in new [] { "NY", "NJ", "MD", "KY" })
            {
                await populationRequest.RequestStream.WriteAsync(new GrpcPopulation.PopulationRequest
                {
                    State = state
                });
            }

            await populationRequest.RequestStream.CompleteAsync();

            var response = await populationRequest.ResponseAsync;

            Console.WriteLine(response.Count);
        }
Esempio n. 19
0
        public void Init()
        {
            var serverCredentials = new SslServerCredentials(new[] { new KeyCertificatePair(File.ReadAllText(TestCredentials.ServerCertChainPath), File.ReadAllText(TestCredentials.ServerPrivateKeyPath)) });

            server = new Server
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports    = { { Host, ServerPort.PickUnused, serverCredentials } }
            };
            server.Start();

            var options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };

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

            var clientCredentials = ChannelCredentials.Create(
                new SslCredentials(File.ReadAllText(TestCredentials.ClientCertAuthorityPath)),
                CallCredentials.FromInterceptor(asyncAuthInterceptor));

            channel = new Channel(Host, server.Ports.Single().BoundPort, clientCredentials, options);
            client  = TestService.NewClient(channel);
        }
        /// <summary>
        /// Adds a delegate that will be used to create <see cref="CallCredentials"/> for a gRPC call.
        /// </summary>
        /// <param name="builder">The <see cref="IHttpClientBuilder"/>.</param>
        /// <param name="authInterceptor">A delegate that is used to create <see cref="CallCredentials"/> for a gRPC call.</param>
        /// <returns>An <see cref="IHttpClientBuilder"/> that can be used to configure the client.</returns>
        public static IHttpClientBuilder AddCallCredentials(this IHttpClientBuilder builder, Func <AuthInterceptorContext, Metadata, IServiceProvider, Task> authInterceptor)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (authInterceptor == null)
            {
                throw new ArgumentNullException(nameof(authInterceptor));
            }

            ValidateGrpcClient(builder);

            builder.Services.Configure <GrpcClientFactoryOptions>(builder.Name, options =>
            {
                options.HasCallCredentials = true;
                options.CallOptionsActions.Add((callOptionsContext) =>
                {
                    var credentials = CallCredentials.FromInterceptor((context, metadata) => authInterceptor(context, metadata, callOptionsContext.ServiceProvider));

                    callOptionsContext.CallOptions = ResolveCallOptionsCredentials(callOptionsContext.CallOptions, credentials);
                });
            });

            return(builder);
        }
Esempio n. 21
0
        public static void Main(string[] args)
        {
            var callCre = CallCredentials.FromInterceptor(MyAsyncAuthInterceptor);

            var cacert     = File.ReadAllText(@"C:\Sertifika\ca.crt");
            var clientcert = File.ReadAllText(@"C:\Sertifika\client.crt");
            var clientkey  = File.ReadAllText(@"C:\Sertifika\client.key");
            var sslCrd     = new SslCredentials(cacert, new KeyCertificatePair(clientcert, clientkey));

            var crd = ChannelCredentials.Create(sslCrd, callCre);

            channel = new Channel("localhost:50051", crd);
            var channel2 = new Channel("localhost:50052", crd);

            var inv = new MyInvoker(new Channel[] { channel, channel2 });

            var client = new Greeter.GreeterClient(inv);

            while (true)
            {
                var user = Console.ReadLine();

                if (user == "q")
                {
                    break;
                }
                var reply = client.SayHello(new HelloRequest {
                    Name = user
                });
                Console.WriteLine("Greeting: " + reply.Message);
            }

            channel.ShutdownAsync().Wait();
            channel2.ShutdownAsync().Wait();
        }
        public async Task MetadataCredentials_ComposedPerCall()
        {
            serviceImpl.StreamingOutputCallHandler = async(req, responseStream, context) =>
            {
                var firstAuth = context.RequestHeaders.Last((entry) => entry.Key == "first_authorization").Value;
                Assert.AreEqual("FIRST_SECRET_TOKEN", firstAuth);
                var secondAuth = context.RequestHeaders.First((entry) => entry.Key == "second_authorization").Value;
                Assert.AreEqual("SECOND_SECRET_TOKEN", secondAuth);
                await responseStream.WriteAsync(new StreamingOutputCallResponse());
            };

            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 call = client.StreamingOutputCall(new StreamingOutputCallRequest {
            },
                                                  new CallOptions(credentials: CallCredentials.Compose(first, second)));

            Assert.IsTrue(await call.ResponseStream.MoveNext());
            Assert.IsFalse(await call.ResponseStream.MoveNext());
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            // Read exported (PEM formatted) server TLS certificate from disk
            var serverCert         = File.ReadAllText("<< ADD PATH TO EXPORTED SERVER CERTIFICATE >>");
            var tlsCertCredentials = new SslCredentials(serverCert);

            // Apply the api key to every request that is made with the client
            var apiKeyCredentials = CallCredentials.FromInterceptor((context, metadata) =>
            {
                metadata.Add("ibahdapi-apikey", "<< ADD API KEY >>");
                return(Task.CompletedTask);
            });

            var combinedCredentials = ChannelCredentials.Create(tlsCertCredentials, apiKeyCredentials);

            // gRPC channel setup to connect to ibaHD-API endpoint in ibaHD-Server
            // Increasing the default message size (~4MB) is recommended
            var channel = new Channel("127.0.0.1:9003", combinedCredentials,
                                      new List <ChannelOption> {
                new ChannelOption(ChannelOptions.MaxReceiveMessageLength, Int32.MaxValue)
            });

            // Instantiate ibaHD-API client on the gRPC channel
            var client = new HdApiService.HdApiServiceClient(channel);

            // Simple request to retrieve stores
            var response = client.GetHdStores(new GetHdStoresRequest());

            // Clean channel shutdown (Check ShutdownAsync() documentation for details)
            channel.ShutdownAsync().Wait();

            Console.WriteLine(response);
            Console.ReadLine();
        }
            protected override async Task Given()
            {
                var node = GetFollowers()[0];
                await Task.WhenAll(node.AdminUserCreated, node.Started);

                using var channel = GrpcChannel.ForAddress(new Uri($"https://{node.HttpEndPoint}"),
                                                           new GrpcChannelOptions {
                    HttpClient = new HttpClient(new SocketsHttpHandler {
                        SslOptions =
                        {
                            RemoteCertificateValidationCallback = delegate { return(true); }
                        }
                    }, true)
                });
                var streamClient = new Streams.StreamsClient(channel);

                using var call = streamClient.Append(new CallOptions(
                                                         credentials: CallCredentials.FromInterceptor((_, metadata) => {
                    metadata.Add("authorization", AuthorizationHeaderValue);
                    return(Task.CompletedTask);
                }),
                                                         deadline: DateTime.UtcNow.AddSeconds(10)));

                await call.RequestStream.WriteAsync(new AppendReq {
                    Options = new AppendReq.Types.Options {
                        NoStream         = new Empty(),
                        StreamIdentifier = new StreamIdentifier {
                            StreamName = ByteString.CopyFromUtf8(ProtectedStream)
                        }
                    }
                });

                await call.RequestStream.WriteAsync(new AppendReq {
                    ProposedMessage = new AppendReq.Types.ProposedMessage {
                        Id = new UUID {
                            String = Uuid.FromGuid(Guid.NewGuid()).ToString()
                        },
                        CustomMetadata = ByteString.Empty,
                        Data           = ByteString.Empty,
                        Metadata       =
                        {
                            { EventStore.Core.Services.Transport.Grpc.Constants.Metadata.Type, "-" }, {
                                EventStore.Core.Services.Transport.Grpc.Constants.Metadata.ContentType,
                                EventStore.Core.Services.Transport.Grpc.Constants.Metadata.ContentTypes
                                .ApplicationOctetStream
                            }
                        }
                    }
                });

                await call.RequestStream.CompleteAsync();

                await call.ResponseHeadersAsync;
                await call.ResponseAsync;

                _status = call.GetStatus();

                await base.Given();
            }
Esempio n. 25
0
        public async Task ClientFactory_CallCredentials_RoundtripToken()
        {
            string?authorization = null;

            Task <HelloReply> UnaryTelemetryHeader(HelloRequest request, ServerCallContext context)
            {
                authorization = context.RequestHeaders.GetValue("authorization");

                return(Task.FromResult(new HelloReply()));
            }

            var method = Fixture.DynamicGrpc.AddUnaryMethod <HelloRequest, HelloReply>(UnaryTelemetryHeader);

            var token       = "token!";
            var credentials = CallCredentials.FromInterceptor((context, metadata) =>
            {
                if (!string.IsNullOrEmpty(token))
                {
                    metadata.Add("Authorization", $"Bearer {token}");
                }
                return(Task.CompletedTask);
            });

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton <ILoggerFactory>(LoggerFactory);
            serviceCollection
            .AddGrpcClient <TestClient <HelloRequest, HelloReply> >(options =>
            {
                options.Address = Fixture.GetUrl(TestServerEndpointName.Http2WithTls);
            })
            .ConfigureChannel(channel =>
            {
                channel.Credentials = ChannelCredentials.Create(new SslCredentials(), credentials);
            })
            .ConfigureGrpcClientCreator(invoker =>
            {
                return(TestClientFactory.Create(invoker, method));
            })
            .ConfigurePrimaryHttpMessageHandler(() =>
            {
                return(new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                });
            });
            var services = serviceCollection.BuildServiceProvider();

            var client = services.GetRequiredService <TestClient <HelloRequest, HelloReply> >();

            var call = client.UnaryCall(new HelloRequest {
                Name = "world"
            });

            await call.ResponseAsync.DefaultTimeout();

            Assert.AreEqual("Bearer token!", authorization);
        }
Esempio n. 26
0
 private CallOptions GetCallOptions()
 {
     return(new(
                credentials : CallCredentials.FromInterceptor((_, metadata) => {
         metadata.Add("authorization", $"{AuthenticationScheme} {AuthenticationValue}");
         return Task.CompletedTask;
     }),
                deadline : DateTime.UtcNow.AddSeconds(5)));
 }
Esempio n. 27
0
        /// <summary>
        /// Gets the authentication token from the robot.
        /// </summary>
        /// <param name="sessionId">The session identifier.</param>
        /// <param name="certificate">The SSL certificate for the robot.</param>
        /// <param name="robotName">Name of the robot.</param>
        /// <param name="ipAddress">The IP address of the robot.</param>
        /// <returns>A task that represents the asynchronous operation; the task result contains the authentication token.</returns>
        /// <exception cref="ArgumentException">
        /// Session ID must be provided - sessionId
        /// or
        /// SSL certificate must be provided - certificate
        /// </exception>
        /// <exception cref="Anki.Vector.Exceptions.VectorAuthenticationException">
        /// Robot name must be provided.
        /// or
        /// Robot name is not in the correct format.
        /// or
        /// IP address must be provided
        /// or
        /// Unable to establish a connection to Vector.
        /// or
        /// Failed to authorize request.  Please be sure to first set up Vector using the companion app.
        /// </exception>
        public static async Task <string> GetTokenGuid(string sessionId, string certificate, string robotName, IPAddress ipAddress)
        {
            if (string.IsNullOrEmpty(sessionId))
            {
                throw new ArgumentException("Session ID must be provided.", nameof(sessionId));
            }
            if (string.IsNullOrEmpty(certificate))
            {
                throw new ArgumentException("SSL certificate must be provided.", nameof(certificate));
            }
            if (string.IsNullOrEmpty(robotName))
            {
                throw new ArgumentException("Robot name must be provided.", nameof(robotName));
            }
            if (!RobotNameIsValid(robotName))
            {
                throw new ArgumentException("Robot name is not in the correct format.", nameof(robotName));
            }
            if (ipAddress == null)
            {
                throw new ArgumentNullException(nameof(ipAddress), "IP address must be provided.");
            }

            // Create the channel
            var channel = new Channel(
                ipAddress.ToString() + ":443",
                ChannelCredentials.Create(new SslCredentials(certificate), CallCredentials.FromInterceptor((context, metadata) => Task.CompletedTask)),
                new ChannelOption[] { new ChannelOption("grpc.ssl_target_name_override", robotName) }
                );

            try
            {
                // Open the channel
                await channel.ConnectAsync(Robot.GrpcDeadline(15_000)).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                // If failed to open channel throw exception
                throw new VectorAuthenticationException(VectorAuthenticationFailureType.Connection, "Unable to establish a connection to Vector.", ex);
            }

            // Create the client and return the response
            var client   = new ExternalInterfaceClient(channel);
            var response = await client.UserAuthenticationAsync(new UserAuthenticationRequest()
            {
                UserSessionId = Google.Protobuf.ByteString.CopyFromUtf8(sessionId),
                ClientName    = Google.Protobuf.ByteString.CopyFromUtf8(Dns.GetHostName())
            });

            if (response.Code != UserAuthenticationResponse.Types.Code.Authorized)
            {
                throw new VectorAuthenticationException(VectorAuthenticationFailureType.Login, "Failed to authorize request.  Please be sure to first set up Vector using the companion app.");
            }
            await channel.ShutdownAsync().ConfigureAwait(false);

            return(response.ClientTokenGuid.ToStringUtf8());
        }
 private ChannelCredentials GetCredentials()
 {
     if (_rootCertificatePath != null)
     {
         var authInterceptor = AuthenticationInterceptors.CreateAuthInterceptor(_token);
         return(ChannelCredentials.Create(new SslCredentials(), CallCredentials.FromInterceptor(authInterceptor)));
     }
     return(ChannelCredentials.Insecure);
 }
Esempio n. 29
0
        public void FromCredential()
        {
            Assert.Null(CallSettings.FromCallCredentials(null));
            AsyncAuthInterceptor interceptor = (context, metadata) => Task.Delay(0);
            var credential = CallCredentials.FromInterceptor(interceptor);
            var settings   = CallSettings.FromCallCredentials(credential);

            Assert.Same(credential, settings.Credentials);
        }
Esempio n. 30
0
        public void MetadataCredentials_PerCall()
        {
            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));
        }