Beispiel #1
0
        private async Task <ChannelCredentials> CreateCredentialsAsync()
        {
            var credentials = ChannelCredentials.Insecure;

            if (options.UseTls.Value)
            {
                credentials = options.UseTestCa.Value ? TestCredentials.CreateSslCredentials() : new SslCredentials();
            }

            if (options.TestCase == "jwt_token_creds")
            {
                var googleCredential = await GoogleCredential.GetApplicationDefaultAsync();

                Assert.IsTrue(googleCredential.IsCreateScopedRequired);
                credentials = ChannelCredentials.Create(credentials, googleCredential.ToCallCredentials());
            }

            if (options.TestCase == "compute_engine_creds")
            {
                var googleCredential = await GoogleCredential.GetApplicationDefaultAsync();

                Assert.IsFalse(googleCredential.IsCreateScopedRequired);
                credentials = ChannelCredentials.Create(credentials, googleCredential.ToCallCredentials());
            }
            return(credentials);
        }
        /// <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);
        }
        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();
        }
Beispiel #4
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.");
                }
            }
        }
    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);
    }
Beispiel #6
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);
        }
Beispiel #7
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();
        }
Beispiel #8
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);
        }
        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);
        }
Beispiel #11
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;
            }
        }
Beispiel #12
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);
        }
Beispiel #13
0
        private async Task ReAuth(CommandContext ctx)
        {
            ctx.LogInfo($"GoogleAssistant: Attempting to refresh access token.");

            using (IAuthorizationCodeFlow flow =
                       new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = KarvisConfiguration.GoogleAssistantConfiguration.ClientId,
                    ClientSecret = KarvisConfiguration.GoogleAssistantConfiguration.ClientSecret
                },
                Scopes = new[] { "https://www.googleapis.com/auth/assistant-sdk-prototype" }
            }))
            {
                var tokenResponse = await flow.RefreshTokenAsync(
                    KarvisConfiguration.GoogleAssistantConfiguration.DebugUser,
                    new GoogleOAuth(KarvisConfiguration).GetRefreshTokenForUser(ctx.User.Id),
                    new CancellationToken());

                new GoogleOAuth(KarvisConfiguration).StoreCredentialsForUser(
                    KarvisConfiguration.GoogleAssistantConfiguration.DebugUser, tokenResponse.AccessToken,
                    tokenResponse.RefreshToken, ctx.User.Id);

                var channelCredentials = ChannelCredentials.Create(new SslCredentials(),
                                                                   GoogleGrpcCredentials.FromAccessToken(tokenResponse.AccessToken));

                UserEmbeddedAssistantClients[ctx.User.Id] =
                    new EmbeddedAssistant.EmbeddedAssistantClient(
                        new Channel("embeddedassistant.googleapis.com", 443, channelCredentials));
            }
        }
        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);
        }
        public LndGrpcService(IConfiguration config)
        {
            /*
             * var certLoc = config.GetValue<string>("cert");
             * var macLoc = config.GetValue<string>("mac");
             * ;
             *
             * var directory = Path.GetFullPath(certLoc);
             * Console.WriteLine(rpc + " stuff " + directory);*/
            var directory = Environment.CurrentDirectory;
            var tls       = File.ReadAllText(directory + "./../lnd-test-cluster/docker/temp/lnd-alice/tls.cert");
            var hexMac    = Util.ToHex(File.ReadAllBytes(directory + "./../lnd-test-cluster/docker/temp/lnd-alice/data/chain/bitcoin/regtest/admin.macaroon"));
            var rpc       = config.GetValue <string>("rpc");

            feePercentage    = config.GetValue <uint>("fee");
            maxSatPerPayment = config.GetValue <uint>("max_sat");
            maxVouchers      = config.GetValue <uint>("max_voucher");
            var macaroonCallCredentials = new MacaroonCallCredentials(hexMac);
            var channelCreds            = ChannelCredentials.Create(new SslCredentials(tls), macaroonCallCredentials.credentials);
            var lndChannel = new Grpc.Core.Channel(rpc, channelCreds);

            client  = new Lightning.LightningClient(lndChannel);
            getInfo = client.GetInfo(new GetInfoRequest());
            Console.WriteLine(getInfo.ToString());
        }
        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));
        }
        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 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());
        }
Beispiel #19
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 static GrpcChannel GetAuthChannel(this NavigationManager navigation, string token) =>
 GrpcChannel.ForAddress(navigation.BaseUri,
                        new GrpcChannelOptions
 {
     HttpClient  = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler())),
     Credentials = ChannelCredentials.Create(new SslCredentials(),
                                             GetJwtCredentials(token))
 });
        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);
        }
 private ChannelCredentials GetCredentials()
 {
     if (_rootCertificatePath != null)
     {
         var authInterceptor = AuthenticationInterceptors.CreateAuthInterceptor(_token);
         return(ChannelCredentials.Create(new SslCredentials(), CallCredentials.FromInterceptor(authInterceptor)));
     }
     return(ChannelCredentials.Insecure);
 }
        /// <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());
        }
Beispiel #24
0
        public async Task Client_CallCredentials_WithLoadBalancing_RoundtripToken()
        {
            // Arrange
            string?authorization = null;

            Task <HelloReply> UnaryMethod(HelloRequest request, ServerCallContext context)
            {
                authorization = context.RequestHeaders.GetValue("authorization");
                return(Task.FromResult(new HelloReply {
                    Message = request.Name
                }));
            }

            var credentials = CallCredentials.FromInterceptor((context, metadata) =>
            {
                metadata.Add("Authorization", $"Bearer TEST");
                return(Task.CompletedTask);
            });

            using var endpoint1 = BalancerHelpers.CreateGrpcEndpoint <HelloRequest, HelloReply>(50051, UnaryMethod, nameof(UnaryMethod), HttpProtocols.Http1AndHttp2, isHttps: true);
            using var endpoint2 = BalancerHelpers.CreateGrpcEndpoint <HelloRequest, HelloReply>(50052, UnaryMethod, nameof(UnaryMethod), HttpProtocols.Http1AndHttp2, isHttps: true);

            var services = new ServiceCollection();

            services.AddSingleton <ResolverFactory>(new StaticResolverFactory(_ => new[]
            {
                new BalancerAddress(endpoint1.Address.Host, endpoint1.Address.Port),
                new BalancerAddress(endpoint2.Address.Host, endpoint2.Address.Port)
            }));
            var socketsHttpHandler = new SocketsHttpHandler
            {
                EnableMultipleHttp2Connections = true,
                SslOptions = new System.Net.Security.SslClientAuthenticationOptions
                {
                    EnabledSslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12,
                    RemoteCertificateValidationCallback = (_, __, ___, ____) => true
                }
            };
            var channel = GrpcChannel.ForAddress("static:///localhost", new GrpcChannelOptions
            {
                LoggerFactory   = LoggerFactory,
                ServiceProvider = services.BuildServiceProvider(),
                Credentials     = ChannelCredentials.Create(new SslCredentials(), credentials),
                HttpHandler     = socketsHttpHandler
            });

            var client = TestClientFactory.Create(channel, endpoint1.Method);

            // Act
            var reply = await client.UnaryCall(new HelloRequest { Name = "Balancer" }).ResponseAsync.DefaultTimeout();

            // Assert
            Assert.AreEqual("Bearer TEST", authorization);
            Assert.AreEqual("Balancer", reply.Message);
        }
Beispiel #25
0
        public static void Main(string[] args)
        {
            var apiKey = "Pj+GIg2/l7ZKmicZi37+1giqKJ1WH3Vt8vSSxCuvPkKD";
            var email  = "*****@*****.**";

            AsyncAuthInterceptor authInterceptor = new AsyncAuthInterceptor((context, metadata) =>
            {
                metadata.Add("Authorization", "Bearer " + apiKey);
                return(Task.FromResult(0));
            });

            var channelCredentials = ChannelCredentials.Create(new SslCredentials(),
                                                               CallCredentials.FromInterceptor(authInterceptor));

            Channel channel = new Channel("api.staging.autheid.com", channelCredentials);

            var client = new Requests.RequestsClient(channel);

            var request = new CreateRequest();

            request.Email           = email;
            request.Title           = "test";
            request.Type            = RequestType.Kyc;
            request.Kyc             = new CreateRequest.Types.KYC();
            request.Kyc.FilesFormat = FileFormat.Embedded;

            var reply = client.Create(request);

            Console.WriteLine("Request ID: " + reply.RequestId);

            var resultRequest = new GetResultRequest();

            resultRequest.RequestId = reply.RequestId;

            var resultReply = client.GetResult(resultRequest);

            Console.WriteLine("Status: " + resultReply.Status);

            if (resultReply.Status == RequestStatus.Success)
            {
                Console.WriteLine("Fist Name: " + resultReply.Kyc.Identification.FirstName);
                Console.WriteLine("Last Name: " + resultReply.Kyc.Identification.LastName);
                Console.WriteLine("File size: " + resultReply.Kyc.KycPdf.Embedded.Length);

                // Create a new file
                using (FileStream fs = System.IO.File.Create("kyc.pdf"))
                {
                    fs.Write(resultReply.Kyc.KycPdf.Embedded.ToByteArray(), 0, resultReply.Kyc.KycPdf.Embedded.Length);
                }
            }

            channel.ShutdownAsync().Wait();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Beispiel #26
0
        public void MetadataCredentials()
        {
            var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(),
                                                               CallCredentials.FromInterceptor(asyncAuthInterceptor));

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

            client.UnaryCall(new SimpleRequest {
            });
        }
Beispiel #27
0
        public async void Init()
        {
            // Add client cert to the handler
            Task AsyncAuthInterceptor(AuthInterceptorContext context, Grpc.Core.Metadata metadata)
            {
                return(Task.Run(() => { metadata.Add("Authorization", $"Bearer {_token}"); }));
            }

            var channelCredentials = new SslCredentials(File.ReadAllText($"{Application.streamingAssetsPath}/server1.crt"));//, //new KeyCertificatePair(File.ReadAllText($"{Application.dataPath}/server1.crt"), ""));

            var callCredentials = CallCredentials.FromInterceptor(AsyncAuthInterceptor);

            Record.Log($"Trying to connect ...");

            _channel = new Channel(
                "127.0.0.1",
                50051,
                ChannelCredentials.Create(
                    channelCredentials,
                    callCredentials)/*,
                                     * new []{ // https://grpc.github.io/grpc/node/grpc.html#~ChannelOptions
                                     * new ChannelOption("grpc.keepalive_permit_without_calls", 1),
                                     * new ChannelOption("grpc.keepalive_time_ms", 5 * 1000), // 5 seconds
                                     * }*/
                );

            await _channel.ConnectAsync(deadline : System.DateTime.UtcNow.AddSeconds(20));

            Record.Log($"gRPC channel status: {_channel.State}");
            _networkClient = new ErutanClient(_channel);
            //var headers = new Grpc.Core.Metadata(); // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
            //headers.Add(new Grpc.Core.Metadata.Entry("grpc-timeout", "2S"));
            _stream = _networkClient.Stream();

            _inStream  = _stream.ResponseStream;
            _outStream = _stream.RequestStream;

            // Listen to server packets on different thread
            _listenerThread = new Thread(Listen)
            {
                IsBackground = true
            };
            _listenerThread.Start();

            // Send packets to server on different thread
            _senderThread = new Thread(DequeuePacketsToBeSent)
            {
                IsBackground = true
            };
            _senderThread.Start();

            StreamConnected?.Invoke();
            IsConnected = true;
        }
        public void ChannelCredentials_CreateComposite()
        {
            var composite = ChannelCredentials.Create(new FakeChannelCredentials(true), new FakeCallCredentials());

            Assert.IsFalse(composite.IsComposable);

            Assert.Throws(typeof(ArgumentNullException), () => ChannelCredentials.Create(null, new FakeCallCredentials()));
            Assert.Throws(typeof(ArgumentNullException), () => ChannelCredentials.Create(new FakeChannelCredentials(true), null));

            // forbid composing non-composable
            Assert.Throws(typeof(ArgumentException), () => ChannelCredentials.Create(new FakeChannelCredentials(false), new FakeCallCredentials()));
        }
        private static GrpcChannel CreateAuthenticatedChannel()
        {
            var sslCredentials       = new SslCredentials();
            var asyncAuthInterceptor = GetAsyncAuthInterceptor();

            var channelCredentials = ChannelCredentials.Create(
                sslCredentials, CallCredentials.FromInterceptor(asyncAuthInterceptor));

            return(GrpcChannel.ForAddress(ConnectionString, new GrpcChannelOptions()
            {
                Credentials = channelCredentials
            }));
        }
Beispiel #30
0
        static void Main(string[] args)
        {
            //CosturaUtility.Initialize();

            // Dummy code that references the troublemaker assemblies "grpc_csharp_ext.x86"
            var callCredentials = CallCredentials.FromInterceptor(async(c, m) => { });
            var credentials     = ChannelCredentials.Create(new SslCredentials(), callCredentials);
            var channel         = new Channel("", credentials); // System.IO.FileNotFoundException happens here

            // We want to get to here without thrown exceptions
            Console.WriteLine("No exceptions thrown!");
            Console.ReadKey();
        }