public async Task Client_CallCredentials_RoundtripToken() { // Arrange 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 options = new GrpcChannelOptions { LoggerFactory = LoggerFactory, Credentials = ChannelCredentials.Create(new SslCredentials(), credentials), HttpHandler = new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator } }; var channel = GrpcChannel.ForAddress(Fixture.GetUrl(TestServerEndpointName.Http2WithTls), options); var client = TestClientFactory.Create <HelloRequest, HelloReply>(channel, method); var call = client.UnaryCall(new HelloRequest { Name = "world" }); // Act await call.ResponseAsync.DefaultTimeout(); Assert.AreEqual("Bearer token!", authorization); }
//private PublisherClient.ClientCreationSettings clientCreationSettings = null; // private PublisherClient.Settings settings = new PublisherClient.Settings(); public PubSub(ILogger <PubSub> logger, IConfiguration configuration) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); string credentialsJsonFilePath = configuration["Application:GoogleApplicationCredentials"]; using (FileStream jsonFileStream = new FileStream(credentialsJsonFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { this.googleCredential = GoogleCredential.FromStream(jsonFileStream); this.channelCredentials = this.googleCredential.ToChannelCredentials(); } //this.clientCreationSettings = new PublisherClient.ClientCreationSettings(credentials: this.channelCredentials); this.logger.LogInformation("PubSub init"); }
private GcpCallInvoker GetCallInvoker(string endpoint, ChannelCredentials credentials, GrpcChannelOptions options, ApiConfig apiConfig, GrpcAdapter adapter) { var effectiveOptions = s_defaultOptions.MergedWith(options ?? GrpcChannelOptions.Empty); apiConfig = apiConfig.Clone(); var key = new Key(endpoint, effectiveOptions, apiConfig, adapter); lock (_lock) { if (!_callInvokers.TryGetValue(key, out GcpCallInvoker callInvoker)) { callInvoker = new GcpCallInvoker(_serviceMetadata, endpoint, credentials, effectiveOptions, apiConfig, adapter); _callInvokers[key] = callInvoker; } return(callInvoker); } }
private static GrpcChannel CreateAuthenticatedChannel(string address, string token) { var credentials = CallCredentials.FromInterceptor((context, metadata) => { metadata.Add("Authorization", $"Bearer {token}"); return(Task.CompletedTask); }); // SslCredentials is used here because this channel is using TLS. // CallCredentials can't be used with ChannelCredentials.Insecure on non-TLS channels. var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions { Credentials = ChannelCredentials.Create(new SslCredentials(), credentials) }); return(channel); }
public PublishSubscribe( IPEndPoint serverEndPoint, IObservable <IEnumerable <DnsEndPoint> > seedsEndpointObservable, ILoggerFactory loggerFactory, ISerializer <byte[]> serializer, ChannelCredentials channelCredentials = null) { _serializer = serializer; PublishSubscribeServerRouter publishSubscribeServerRouter = new PublishSubscribeServerRouter(loggerFactory, topic => new DefaultTopicFilter(topic)); RegisterDisposable(publishSubscribeServerRouter); Server server = new Server { Services = { PubSubService.BindService(publishSubscribeServerRouter) }, Ports = { new ServerPort(serverEndPoint.Address.ToString(), serverEndPoint.Port, ServerCredentials.Insecure) } }; server.Start(); seedsEndpointObservable .Select(seedEndPoints => seedEndPoints .Select(dnsEndPoint => new Channel(dnsEndPoint.Host, dnsEndPoint.Port, channelCredentials ?? ChannelCredentials.Insecure)) .Select(channel => new PubSubService.PubSubServiceClient(channel))) .Subscribe(_clientsSource, CancellationToken); ILogger <PublishSubscribe> logger = loggerFactory.CreateLogger <PublishSubscribe>(); _clientsSource .SelectMany(clients => clients.Select(client => client.Publish().RequestStream)) .CombineLatest(_publishSubject, (streamWriter, message) => { try { streamWriter.WriteAsync(message).GetAwaiter().GetResult(); } catch (Exception e) { logger.LogError(e, "Error while sending message"); } return(Unit.Default); }) .Subscribe(CancellationToken); }
public LibraClient(LibraNetwork network) { this.Network = network; switch (network) { case LibraNetwork.Testnet: Host = Constant.ServerHosts.TestnetAdmissionControl; Port = 80; ChannelCredentials = ChannelCredentials.Insecure; FaucetServerHost = Constant.ServerHosts.TestnetFaucet; break; } Channel channel = new Channel(Host, Port, ChannelCredentials); acClient = new AdmissionControlClient(channel); }
/// <summary> /// Create a secure grpc channel by attaching the jwt auth token to any outgoing grpc request /// </summary> public static ChannelCredentials CreateSecureChannel(IServiceProvider serviceProvider) { var credentials = CallCredentials.FromInterceptor((context, metadata) => { var _httpContext = serviceProvider.GetService <IHttpContextAccessor>().HttpContext; if (_httpContext != null && _httpContext.Request.Headers.Any() && !string.IsNullOrEmpty(_httpContext.Request.Headers["Authorization"])) { metadata.Add("Authorization", _httpContext.Request.Headers["Authorization"]); } return(Task.CompletedTask); }); return(ChannelCredentials.Create(new SslCredentials(), credentials)); }
private static GrpcChannel CreateAuthenticatedAChannel(string address) { var credentials = CallCredentials.FromInterceptor((context, metadata) => { if (!string.IsNullOrEmpty(_token)) { metadata.Add("Authorization", $"Bearer {_token}"); } return(Task.CompletedTask); }); var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions { Credentials = ChannelCredentials.Create(new SslCredentials(), credentials) }); return(channel); }
public void MetadataCredentials_InterceptorThrows() { var authInterceptorExceptionMessage = "Auth interceptor throws"; var callCredentials = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => { throw new Exception(authInterceptorExceptionMessage); })); 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.Unavailable, ex.Status.StatusCode); StringAssert.Contains(authInterceptorExceptionMessage, ex.Status.Detail); }
public RestChannel(RestServiceCollection serviceCollection, string endpoint, ChannelCredentials credentials, GrpcChannelOptions options) : base(endpoint) { _serviceCollection = serviceCollection; // Reuse a single CallInvoker however many times CreateCallInvoker is called. _callInvoker = new RestCallInvoker(this); // TODO: Handle endpoints better... var baseAddress = new Uri($"https://{endpoint}"); // TODO: Avoid creating an HTTP Client for every channel? _httpClient = new HttpClient { BaseAddress = baseAddress }; _channelAuthInterceptor = credentials.ToAsyncAuthInterceptor(); // TODO: Use options where appropriate. }
internal SpannerClientCreationOptions(SpannerConnectionStringBuilder builder) { var emulatorBuilder = new SpannerClientBuilder { EmulatorDetection = builder.EmulatorDetection, EnvironmentVariableProvider = builder.EnvironmentVariableProvider }.MaybeCreateEmulatorClientBuilder(); UsesEmulator = emulatorBuilder is object; // If the client connects to the emulator use its endpoint (regardless of builder.Endpoint) Endpoint = emulatorBuilder?.Endpoint ?? builder.EndPoint; _credentialsFile = builder.CredentialFile; // If the client connects to the emulator, use its credentials (regardless of builder.CredentialOverride) _credentialsOverride = emulatorBuilder?.ChannelCredentials ?? builder.CredentialOverride; MaximumGrpcChannels = builder.MaximumGrpcChannels; MaximumConcurrentStreamsLowWatermark = (uint)builder.MaxConcurrentStreamsLowWatermark; }
/// <summary> /// Creates the channel for the new service, and sets the proxy server. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The new channel.</returns> private Channel CreateChannel(GoogleAdsConfig config) { ChannelCredentials channelCredentials = GoogleGrpcCredentials.ToChannelCredentials(config.Credentials); if (config.Proxy == null) { Environment.SetEnvironmentVariable("http_proxy", null); } else { Environment.SetEnvironmentVariable("http_proxy", config.Proxy.Address.ToString()); } Uri uri = new Uri(config.ServerUrl); return(new Channel(uri.Host, uri.Port, channelCredentials, null)); }
private void Start() { // ボタンを押したときのイベントを追加 button.onClick.AddListener(() => { var str = inputField.text; if (string.IsNullOrEmpty(str)) { return; } inputField.text = ""; CreateRequest(str); Debug.Log($"Send Request: {str}"); }); // 認証情報をResourceから読み込む var credentialStr = Resources.Load <TextAsset>(credential).text; var googleCredential = GoogleCredential.FromJson(credentialStr); _credentials = googleCredential.CreateScoped(GcpUrl).ToChannelCredentials(); var channel = new Channel(ChannelTarget, _credentials); _client = new TextToSpeechClientImpl(new TextToSpeech.TextToSpeechClient(channel), new TextToSpeechSettings()); // オプションを記述 _audioConfig = new AudioConfig() { AudioEncoding = AudioEncoding.Linear16, SampleRateHertz = 44100 }; // 声のパラメータを指定 // https://cloud.google.com/text-to-speech/docs/voices?hl=jaに記載されているものから選択できます _voiceSelectionParams = new VoiceSelectionParams() { SsmlGender = SsmlVoiceGender.Female, Name = "ja-JP-Wavenet-B", LanguageCode = "ja-JP" }; _context = SynchronizationContext.Current; }
private static bool IsServingLoadBalancerEndpoint( [NotNull] Channel channel, [NotNull] ChannelCredentials credentials, string serviceName, int enoughForLargeGeometries) { var channelHealth = new Health.HealthClient(channel); bool isServingEndpoint = GrpcUtils.IsServing(channelHealth, serviceName, out _); if (isServingEndpoint) { return(false); } bool isLoadBalancer = GrpcUtils.IsServing(channelHealth, nameof(ServiceDiscoveryGrpc), out StatusCode lbStatusCode); if (isLoadBalancer) { _msg.DebugFormat("{0} is a load balancer address.", channel.ResolvedTarget); Channel suggestedLocation = TryGetChannelFromLoadBalancer(channel, credentials, serviceName, enoughForLargeGeometries); if (suggestedLocation != null) { _msg.DebugFormat("Using serving load balancer at {0}", channel.ResolvedTarget); return(true); } // Assumption: A load balancer is never also serving real requests -> lets not use it at all! _msg.Debug( "The load balancer has no service locations available. It will not be used."); return(false); } _msg.DebugFormat("No {0} service and no serving load balancer at {1}. Error code: {2}", serviceName, channel.ResolvedTarget, lbStatusCode); return(false); }
static GrpcChannel GetChannel(string address, string token) { var credentials = CallCredentials.FromInterceptor((context, metadata) => { if (!string.IsNullOrEmpty(token)) { metadata.Add("Authorization", $"{tokenSchema} {token}"); } return(Task.CompletedTask); }); var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions { Credentials = ChannelCredentials.Create(new SslCredentials(), credentials), HttpHandler = GetHttpHandler() }); return(channel); }
private Channel GetChannel(ServiceLocation serviceLocation) { if (!_channelCache.TryGetValue(serviceLocation, out Channel channel)) { ChannelCredentials channelCredentials = GrpcUtils.CreateChannelCredentials( serviceLocation.UseTls, _clientCertificate); channel = GrpcUtils.CreateChannel(serviceLocation.HostName, serviceLocation.Port, channelCredentials); if (!_channelCache.TryAdd(serviceLocation, channel)) { // It's been added in the meanwhile by another request on another thread channel = _channelCache[serviceLocation]; } } return(channel); }
public async void Connect(string url, ChannelCredentials channelCredentials) { try { Channel = new Channel(url, channelCredentials); RoomService = MagicOnionClient.Create <IGetRoomService>(Channel); IsConnect = true; ConnectServerUI.alpha = 0; Others.ForEach(x => x.alpha = 1); } catch (Exception e) { } RefreshRoomList(); }
public static AnalyzeSyntaxResponse AnalyzeSyntax(string texto) { GoogleCredential credential = GoogleCredential.FromFile(JSON_PATH); ChannelCredentials channelCredentials = credential.ToChannelCredentials(); var builder = new LanguageServiceClientBuilder(); builder.ChannelCredentials = channelCredentials; var client = builder.Build(); var syntax = client.AnalyzeSyntax(new Document() { Content = texto, Type = Document.Types.Type.PlainText, Language = "en-US" }); return(syntax); }
public Runner(RunnerArgs args, IReceiveMessageHandler handler) { string jsonpath = args.ServiceAccountJsonFpath; string projectId = args.PubSubProjectId; string subscriptionId = args.PubSubSubscriptionId; GoogleCredential googleCredential = GoogleCredential.FromFile(jsonpath).CreateScoped(SCOPES); ChannelCredentials channelCredentials = googleCredential.ToChannelCredentials(); Channel channel = new Channel(SubscriberServiceApiClient.DefaultEndpoint.Host, SubscriberServiceApiClient.DefaultEndpoint.Port, channelCredentials); SubscriberServiceApiClient subscriberService = SubscriberServiceApiClient.Create(channel); SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId); SubscriberClient.ClientCreationSettings settings = new SubscriberClient.ClientCreationSettings(credentials: channelCredentials); SubscriberClient subscriber = SubscriberClient.CreateAsync(subscriptionName, settings).Result; this._factory = new MessageFactory(googleCredential); this._subscriber = subscriber; this._handler = handler; }
public void ReleaseClient(SpannerClient spannerClient, ChannelCredentials credentials = null, ServiceEndpoint endpoint = null, IDictionary additionalOptions = null) { if (spannerClient != null) { var key = new ClientCredentialKey(credentials, endpoint, additionalOptions); CredentialClientPool poolEntry; if (_clientPoolByCredential.TryGetValue(key, out poolEntry)) { poolEntry.ReleaseClient(spannerClient); } else { Logger.Error(() => "An attempt was made to release an unrecognized spanner client to the pool."); } } }
internal ZeebeClient(string address, ChannelCredentials credentials, TimeSpan?keepAlive, ILoggerFactory loggerFactory = null) { this.loggerFactory = loggerFactory; var channelOptions = new List <ChannelOption>(); var userAgentString = "client: csharp, version: " + typeof(ZeebeClient).Assembly.GetName().Version; var userAgentOption = new ChannelOption(ChannelOptions.PrimaryUserAgentString, userAgentString); channelOptions.Add(userAgentOption); AddKeepAliveToChannelOptions(channelOptions, keepAlive); channelToGateway = new Channel(address, credentials, channelOptions); gatewayClient = new Gateway.GatewayClient(channelToGateway); }
private static async Task CallCertificateInfoAsync(bool includeClientCertificate) { try { Console.WriteLine($"Setting up HttpClient has certificate:{includeClientCertificate}"); var httpClient = CreateHttpClient(includeClientCertificate); var callCredential = CallCredentials.FromInterceptor((context, metadata) => { metadata.Add("Authorization", $"Bearer {CreateCertificateInfo().GetRawCertDataString()}"); return(Task.CompletedTask); }); var channelCredentials = ChannelCredentials.Create(new SslCredentials(), callCredential); var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions { HttpClient = httpClient, Credentials = channelCredentials }); var client = new Certifier.CertifierClient(channel); Console.WriteLine("Sending gRPC call..."); var certificateInfo = await client.GetCertificateInfoAsync(new Empty()); Console.WriteLine($"Server received client certificate:{ certificateInfo.HasCertificate}"); if (certificateInfo.HasCertificate) { Console.WriteLine($"Client certificate name:{certificateInfo.Name}"); } } catch (RpcException ex) { Console.WriteLine($"gRPC error from calling service:{ex.Status.Detail}"); } catch (Exception ex) { Console.WriteLine($"Unexpected error calling service." + ex.Message); throw; } }
public static GrpcChannel Create(string address, string apiKey) { var credentials = CallCredentials.FromInterceptor((context, metadata) => { if (!string.IsNullOrEmpty(apiKey)) { metadata.Add("DG-Auth", apiKey); } return(Task.CompletedTask); }); // SslCredentials is used here because this channel is using TLS. // CallCredentials can't be used with ChannelCredentials.Insecure on non-TLS channels. var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions { Credentials = ChannelCredentials.Create(new SslCredentials(), credentials) }); return(channel); }
public TradingApiClient(string grpcUrl, string apiKey) { var credentials = CallCredentials.FromInterceptor((context, metadata) => { if (!string.IsNullOrEmpty(apiKey)) { metadata.Add("Authorization", $"Bearer {apiKey}"); } return(Task.CompletedTask); }); Channel = GrpcChannel.ForAddress(grpcUrl, new GrpcChannelOptions { Credentials = ChannelCredentials.Create(new SslCredentials(), credentials) }); PublicApi = new PublicService.PublicServiceClient(Channel); PrivateApi = new PrivateService.PrivateServiceClient(Channel); }
public Lightning(string tlsLocation, string macaroonLocation, string ip) { tls = File.ReadAllText(tlsLocation); sslCreds = new SslCredentials(tls); byte[] macaroonBytes = File.ReadAllBytes(macaroonLocation); macaroon = BitConverter.ToString(macaroonBytes).Replace("-", ""); // hex format stripped of "-" chars Task AddMacaroon(AuthInterceptorContext context, Metadata metadata) { metadata.Add(new Metadata.Entry("macaroon", macaroon)); return(Task.CompletedTask); } var macaroonInterceptor = new AsyncAuthInterceptor(AddMacaroon); var combinedCreds = ChannelCredentials.Create(sslCreds, CallCredentials.FromInterceptor(macaroonInterceptor)); var channel = new Grpc.Core.Channel(ip, combinedCreds); client = new Lnrpc.Lightning.LightningClient(channel); }
/// <summary> /// Configures a <see cref="DbContextOptionsBuilder"/> for use with Cloud Spanner. /// </summary> /// <param name="optionsBuilder">The DbContextOptionsBuilder to configure for use with Cloud Spanner</param> /// <param name="connection">The connection to use to connect to Cloud Spanner</param> /// <param name="spannerOptionsAction">Any actions that should be executed as part of configuring the options builder for Cloud Spanner</param> /// <param name="channelCredentials">An optional credential for operations to be performed on the Spanner database.</param> /// <returns>The optionsBuilder for chaining</returns> internal static DbContextOptionsBuilder UseSpanner( this DbContextOptionsBuilder optionsBuilder, SpannerRetriableConnection connection, Action <SpannerDbContextOptionsBuilder> spannerOptionsAction = null, ChannelCredentials channelCredentials = null) { GaxPreconditions.CheckNotNull(optionsBuilder, nameof(optionsBuilder)); GaxPreconditions.CheckNotNull(connection, nameof(connection)); SpannerModelValidationConnectionProvider.Instance.SetConnectionString(connection.ConnectionString, channelCredentials); var extension = (SpannerOptionsExtension)GetOrCreateExtension(optionsBuilder).WithConnection(connection); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); ConfigureWarnings(optionsBuilder); spannerOptionsAction?.Invoke(new SpannerDbContextOptionsBuilder(optionsBuilder)); return(optionsBuilder); }
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 channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions { Credentials = ChannelCredentials.Create(new SslCredentials(), credentials) }); return(channel); }
private async Task <GrpcChannel> CreateServiceChannel() { var address = _config["Api:Chat"]; var user = await _currentUserService.CurrentUser(); var credentials = CallCredentials.FromInterceptor((context, metadata) => { if (!string.IsNullOrEmpty(user.AccessToken)) { metadata.Add("Authorization", $"Bearer {user.AccessToken}"); } return(Task.CompletedTask); }); var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions { Credentials = ChannelCredentials.Create(new SslCredentials(), credentials) }); return(channel); }
public static GrpcChannel CreateAuthenticatedChannel(string address, IHttpContextAccessor httpContext) { var credentials = CallCredentials.FromInterceptor(async(context, metadata) => { var accessToken = await httpContext.HttpContext.GetTokenAsync("access_token"); if (!string.IsNullOrEmpty(accessToken)) { metadata.Add("Authorization", $"Bearer {accessToken}"); } }); // SslCredentials is used here because this channel is using TLS. // Channels that aren't using TLS should use ChannelCredentials.Insecure instead. var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions { Credentials = ChannelCredentials.Create(new SslCredentials(), credentials) }); return(channel); }
/// <summary> /// Starting point of the Google Streaming Speech-to-Text program. /// </summary> /// <param name="args">First argument must be the path to the credentials JSON file.</param> static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Usage: GoogleCloudSpeech.exe [path to credentials JSON file]"); } else { // Create client var fileStream = new FileStream(args[0], FileMode.Open); GoogleCredential googleCredential = GoogleCredential.FromStream(fileStream); ChannelCredentials channelCredentials = GoogleGrpcCredentials.ToChannelCredentials(googleCredential); m_Channel = new Channel("speech.googleapis.com", channelCredentials); m_Client = new Speech.SpeechClient(m_Channel); // Wait to begin streaming Console.WriteLine("ready to start"); while (Console.ReadLine() != "start") { ; } Console.WriteLine("start streaming"); Task streamingTask = StreamingRequest(); // Check for input files string input; while ((input = Console.ReadLine()) != "stop") { m_AudioChunksQueue.Enqueue(ByteString.CopyFrom(File.ReadAllBytes(input))); Console.WriteLine("received audio file input"); } // Finish streaming and wait for the request to finish Console.WriteLine("stop streaming"); m_DoneStreaming = true; streamingTask.Wait(); m_Channel.ShutdownAsync().Wait(); } }