Example #1
0
        static void Main(string[] args)
        {
            var t = GoogleCredential.GetApplicationDefaultAsync();

            t.Wait();
            var credential = t.Result;

            WriteLine($"Google default application credential is null? {credential == null}");
            ReadKey();
        }
Example #2
0
        private async Task <ChannelCredentials> CreateChannelCredentialsUncached()
        {
            var appDefaultCredentials = await GoogleCredential.GetApplicationDefaultAsync().ConfigureAwait(false);

            if (appDefaultCredentials.IsCreateScopedRequired)
            {
                appDefaultCredentials = appDefaultCredentials.CreateScoped(_scopes);
            }
            return(appDefaultCredentials.ToChannelCredentials());
        }
Example #3
0
        private async Task <GoogleCredential> GetCredentialAsync()
        {
            var credential = await GoogleCredential.GetApplicationDefaultAsync();

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(_configuration["vm_conf:credential_url"]);
            }

            return(credential);
        }
Example #4
0
        public DlpTestFixture()
        {
            ProjectId = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
            // Authorize the client using Application Default Credentials.
            // See: https://developers.google.com/identity/protocols/application-default-credentials
            GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;

            // Fetch the test key from an environment variable
            KeyName    = Environment.GetEnvironmentVariable("DLP_DEID_KEY_NAME");
            WrappedKey = Environment.GetEnvironmentVariable("DLP_DEID_WRAPPED_KEY");
        }
        private IConfigurableHttpClientInitializer GetApplicationDefaultCredentials()
        {
            // Loads credentials from file pointed to by GOOGLE_APPLICATION_CREDENTIALS environmental variable.
            var credential = GoogleCredential.GetApplicationDefaultAsync().Result;

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(StorageService.Scope.DevstorageReadWrite);
            }
            return(credential);
        }
Example #6
0
        /// <summary>
        /// Attempts to load the application default credentials
        /// </summary>
        /// <returns>The application default credentials, or null if none were found.</returns>
        private static ICredential LoadApplicationDefaultCredentials()
        {
            try {
                GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;
                return(credential.CreateScoped(scopes));
            } catch (Exception) {
                // No application default credentials, continue to try other options.
            }

            return(null);
        }
        public async Task SignedURLPut()
        {
            var bucketName = _fixture.BucketName;
            var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential;
            var httpClient = new HttpClient();

            // Sample: SignedURLPut
            // Create a signed URL which allows the requester to PUT data with the text/plain content-type.
            UrlSigner urlSigner   = UrlSigner.FromServiceAccountCredential(credential);
            var       destination = "places/world.txt";
            string    url         = urlSigner.Sign(
                bucketName,
                destination,
                TimeSpan.FromHours(1),
                HttpMethod.Put,
                contentHeaders: new Dictionary <string, IEnumerable <string> > {
                { "Content-Type", new[] { "text/plain" } }
            });

            // Upload the content into the bucket using the signed URL.
            string source = "world.txt";

            ByteArrayContent content;

            using (FileStream stream = File.OpenRead(source))
            {
                byte[] data = new byte[stream.Length];
                stream.Read(data, 0, data.Length);
                content = new ByteArrayContent(data)
                {
                    Headers = { ContentType = new MediaTypeHeaderValue("text/plain") }
                };
            }

            HttpResponseMessage response = await httpClient.PutAsync(url, content);

            // End sample

            Assert.True(response.IsSuccessStatusCode);

            var client = StorageClient.Create();
            var result = new MemoryStream();
            await client.DownloadObjectAsync(bucketName, destination, result);

            using (var stream = File.OpenRead(source))
            {
                var data = new byte[stream.Length];
                stream.Read(data, 0, data.Length);
                Assert.Equal(result.ToArray(), data);
            }

            await client.DeleteObjectAsync(bucketName, destination);
        }
        public async Task SignedUrlWithIamServiceBlobSigner()
        {
            _fixture.SkipIf(Platform.Instance().Type == PlatformType.Unknown);

            var bucketName = _fixture.BucketName;
            var objectName = _fixture.HelloStorageObjectName;
            var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential;
            var httpClient = new HttpClient();

            // Sample: IamServiceBlobSignerUsage
            // First obtain the email address of the default service account for this instance from the metadata server.
            HttpRequestMessage serviceAccountRequest = new HttpRequestMessage
            {
                // Note: you could use 169.254.169.254 as the address to avoid a DNS lookup.
                RequestUri = new Uri("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email"),
                Headers    = { { "Metadata-Flavor", "Google" } }
            };
            HttpResponseMessage serviceAccountResponse = await httpClient.SendAsync(serviceAccountRequest).ConfigureAwait(false);

            serviceAccountResponse.EnsureSuccessStatusCode();
            string serviceAccountId = await serviceAccountResponse.Content.ReadAsStringAsync();

            // Create an IAM service client object using the default application credentials.
            GoogleCredential iamCredential = await GoogleCredential.GetApplicationDefaultAsync();

            iamCredential = iamCredential.CreateScoped(IamService.Scope.CloudPlatform);
            IamService iamService = new IamService(new BaseClientService.Initializer
            {
                HttpClientInitializer = iamCredential
            });

            // Create a URL signer that will use the IAM service for signing. This signer is thread-safe,
            // and would typically occur as a dependency, e.g. in an ASP.NET Core controller, where the
            // same instance can be reused for each request.
            IamServiceBlobSigner blobSigner = new IamServiceBlobSigner(iamService, serviceAccountId);
            UrlSigner            urlSigner  = UrlSigner.FromBlobSigner(blobSigner);

            // Use the URL signer to sign a request for the test object for the next hour.
            string url = await urlSigner.SignAsync(
                bucketName,
                objectName,
                TimeSpan.FromHours(1),
                HttpMethod.Get);

            // Prove we can fetch the content of the test object with a simple unauthenticated GET request.
            HttpResponseMessage response = await httpClient.GetAsync(url);

            string content = await response.Content.ReadAsStringAsync();

            // End sample

            Assert.Equal(_fixture.HelloWorldContent, content);
        }
Example #9
0
        public async ValueTask <string> GetAccessTokenAsync(HashSet <string> scopes, CancellationToken cancellationToken)
        {
            if (null == _googleCredential)
            {
                _googleCredential = await GoogleCredential.GetApplicationDefaultAsync();
            }
            var scopedCredentials = _scopedCredentials.GetOrAdd(scopes, _scopedFactory);

            return(await scopedCredentials
                   .UnderlyingCredential
                   .GetAccessTokenForRequestAsync(cancellationToken : cancellationToken));
        }
Example #10
0
        GetApplicationDefaultCredentials()
        {
            GoogleCredential credential =
                GoogleCredential.GetApplicationDefaultAsync().Result;

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[] {
                    StorageService.Scope.DevstorageReadWrite
                });
            }
            return(credential);
        }
Example #11
0
        private async Task Run()
        {
// 1. no basic auth, with usercredentials
// need to set export http_proxy=http://localhost:3128 for Pubsub
// need to set ProxySupportedHttpClientFactory for GCS and oauth2

//  auth Y
//  gcs Y
//  pubsub Y


// 1638323879.659    693 192.168.9.1 TCP_TUNNEL/200 45147 CONNECT storage.googleapis.com:443 - HIER_DIRECT/172.253.63.128 -
// 1638323879.659    884 192.168.9.1 TCP_TUNNEL/200 7349 CONNECT oauth2.googleapis.com:443 - HIER_DIRECT/142.251.45.10 -
// 1638323879.659    372 192.168.9.1 TCP_TUNNEL/200 7878 CONNECT pubsub.googleapis.com:443 - HIER_DIRECT/172.217.13.234 -


// 2. no basic auth, with service account credentials
// export GOOGLE_APPLICATION_CREDENTIALS=/path/to/svc_account.json
//  auth N
//  gcs N
//  pubsub Y

// 3. no basicauth, with ServiceAccountCredential
            //var stream = new FileStream("/path/to/svc_account.json", FileMode.Open, FileAccess.Read);
            //ServiceAccountCredential sacredential = ServiceAccountCredential.FromServiceAccountData(stream);
            GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();

            credential = credential.CreateWithHttpClientFactory(new ProxySupportedHttpClientFactory());

            StorageService service = new StorageService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = StorageClientImpl.ApplicationName,
                HttpClientFactory     = new ProxySupportedHttpClientFactory(),
            });
            var client = new StorageClientImpl(service, null);

            foreach (var b in client.ListBuckets(projectID))
            {
                Console.WriteLine(b.Name);
            }

            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            ProjectName projectName             = ProjectName.FromProject(projectID);

            foreach (Topic t in publisher.ListTopics(projectName))
            {
                Console.WriteLine(t.Name);
            }
        }
        private async Task <GoogleCredential> GetGoogleSheetCredentials(string credentialFilePath)
        {
            var credentialAsJson = Environment.GetEnvironmentVariable(GoogleApplicationCredentialsAsJson);

            if (credentialAsJson != null)
            {
                return(GoogleCredential.FromJson(credentialAsJson));
            }

            return(credentialFilePath switch
            {
                null or "" => await GoogleCredential.GetApplicationDefaultAsync(),
                _ => await GoogleCredential.FromFileAsync(credentialFilePath, CancellationToken.None)
            });
Example #13
0
        private async Task <GoogleCredential> AuthorizedAsync(dynamic secureOptions)
        {
            switch (secureOptions.CloudSecure)
            {
            case CloudSecureOptions.defualt:
                return(await GoogleCredential.GetApplicationDefaultAsync());

            case CloudSecureOptions.file:
                return(await GoogleCredential.FromJson(secureOptions.SecureFileLocation));

            default:
                return(await GoogleCredential.GetApplicationDefaultAsync());
            }
        }
Example #14
0
        public static VisionService CreateDefaultAuthorizedClient()
        {
            var credential = GoogleCredential.GetApplicationDefaultAsync().Result;

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[] { VisionService.Scope.CloudPlatform });
            }
            return(new VisionService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                GZipEnabled = false
            }));
        }
        /// <summary>
        /// Helper to create a channel from a host, port and optional credentials.
        /// </summary>
        /// <param name="host">The host to connect to.</param>
        /// <param name="port">The port to connect to.</param>
        /// <param name="credentials">The credentials to use, or null to use application default credentials.</param>
        /// <returns></returns>
        internal static async Task <Channel> CreateChannelAsync(string host, int port, ChannelCredentials credentials)
        {
            if (credentials == null)
            {
                var appDefaultCredentials = await GoogleCredential.GetApplicationDefaultAsync().ConfigureAwait(false);

                if (appDefaultCredentials.IsCreateScopedRequired)
                {
                    appDefaultCredentials = appDefaultCredentials.CreateScoped(SpannerClient.DefaultScopes);
                }
                credentials = appDefaultCredentials.ToChannelCredentials();
            }

            return(new Channel(host, port, credentials));
        }
Example #16
0
        /// <summary>
        /// Uses GOOGLE_APPLICATION_CREDENTIALS to locate key file.
        /// </summary>
        /// <returns></returns>
        public static async Task <BigtableCredentials> UseEnvironmentAsync()
        {
            // Hookup .pem file
            SetDefaultSslKeyFilePath();

            // Make sure user did it right!
            EnsureEnvironmentVariableExists(BigtableConstants.EnvironmentVariables.ApplicationCredentialsFilePath);
            EnsureEnvironmentVariableExists(BigtableConstants.EnvironmentVariables.SslRootFilePath);

            // Get credential
            var credentials = await GoogleCredential.GetApplicationDefaultAsync();

            // Return results
            return(new BigtableCredentials(credentials));
        }
Example #17
0
        /// <summary>
        /// Synchronously creates a <see cref="StorageClient"/>, using application default credentials if
        /// no credentials are specified.
        /// </summary>
        /// <remarks>
        /// The credentials are scoped as necessary.
        /// </remarks>
        /// <param name="credential">Optional <see cref="GoogleCredential"/>.</param>
        /// <returns>The created <see cref="StorageClient"/>.</returns>
        public static StorageClient Create(GoogleCredential credential = null)
        {
            credential = credential ?? Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(StorageService.Scope.DevstorageFullControl);
            }
            var service = new StorageService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = StorageClientImpl.ApplicationName,
            });

            return(new StorageClientImpl(service));
        }
    async Task <GmailService> GetService()
    {
        var cred = await GoogleCredential.GetApplicationDefaultAsync();

        cred = cred.CreateScoped(Scopes)
               .CreateWithUser(_config.FromEmailAddress);

        var svc = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = cred,
            ApplicationName       = _config.ApplicationName
        });

        return(svc);
    }
Example #19
0
        public static GoogleCredential FetchCredential(IConfiguration configuration)
        {
            // Use the default credentials if the environment variable is set.
            if (Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") != null)
            {
                return(GoogleCredential.GetApplicationDefaultAsync().Result);
            }
            string           secretUri    = configuration["APPSETTING_SecretUri"];
            string           clientId     = configuration["APPSETTING_ClientId"];
            string           clientSecret = configuration["APPSETTING_ClientSecret"];
            ClientCredential credential   = new ClientCredential(clientId, clientSecret);
            var secret = GetKeyVaultSecret(credential, secretUri);

            return(GoogleCredential.FromStream(new MemoryStream(Encoding.UTF8.GetBytes(secret))));
        }
Example #20
0
        public async static Task Run()
        {
            string CRED_PATH = new Factory.FileFactory().GetFolder() + @"\api_key\My First Project-ca909aeb1219.json";


            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", CRED_PATH);

            GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();

            var service = new Oauth2Service(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Oauth2 Sample",
            }
                                            );
        }
Example #21
0
        public async Task AuthImplicit(string projectId)
        {
            // If you don't specify credentials when constructing the client, the
            // client library will look for credentials in the environment.
            var credential = await GoogleCredential.GetApplicationDefaultAsync();

            // var storage = StorageClient.Create(credential);
            // Make an authenticated API request.
            // var buckets = storage.ListBuckets(projectId);
            // foreach (var bucket in buckets)
            // {
            //     Console.WriteLine(bucket.Name);
            // }

            await Task.FromResult(0);
        }
Example #22
0
        public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client, string oauthScope)
        {
            Console.WriteLine("running per_rpc_creds");
            ITokenAccess googleCredential = await GoogleCredential.GetApplicationDefaultAsync();

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

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

            Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username);
            Console.WriteLine("Passed!");
        }
Example #23
0
 public PubsubFixture()
 {
     GrpcInfo.EnableSubchannelCounting();
     _projectNumber = new Lazy <Task <string> >(async() =>
     {
         var cred = await GoogleCredential.GetApplicationDefaultAsync().ConfigureAwait(false);
         cred     = cred.CreateScoped(CloudResourceManagerService.Scope.CloudPlatformReadOnly);
         var crm  = new CloudResourceManagerService(new BaseClientService.Initializer
         {
             HttpClientInitializer = cred,
             ApplicationName       = "pubsub integration test",
         });
         var project = await crm.Projects.Get(ProjectId).ExecuteAsync().ConfigureAwait(false);
         return(project.ProjectNumber.ToString());
     });
 }
        /// <summary>
        /// Create the Error Reporting service (<seealso cref="ClouderrorreportingService"/>)
        /// with the Application Default Credentials and the proper scopes.
        /// See: https://developers.google.com/identity/protocols/application-default-credentials.
        /// </summary>
        private static ClouderrorreportingService CreateErrorReportingClient()
        {
            // Get the Application Default Credentials.
            GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;

            // Add the needed scope to the credentials.
            credential.CreateScoped(ClouderrorreportingService.Scope.CloudPlatform);

            // Create the Error Reporting Service.
            ClouderrorreportingService service = new ClouderrorreportingService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
            });

            return(service);
        }
Example #25
0
        private async Task Run()
        {
            // export GOOGLE_APPLICATION_CREDENTIALS=/path/to/svc_account.json

            GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();

            //var stream = new FileStream("/path/to/svc_account.json", FileMode.Open, FileAccess.Read);
            //ServiceAccountCredential credential = ServiceAccountCredential.FromServiceAccountData(stream);
            var    client     = StorageClient.Create();
            string project_id = "your-project";

            foreach (var obj in client.ListObjects(project_id, ""))
            {
                Console.WriteLine(obj.Name);
            }
        }
        //TODO: ASync
        private void CallCloudVision(Android.Graphics.Bitmap bitmap)
        {
            mImageDetails.SetText(Resource.String.loading_message);

            GoogleCredential credential =
                GoogleCredential.GetApplicationDefaultAsync().Result;

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    VisionService.Scope.CloudPlatform
                });
            }
            var vision = new VisionService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                GZipEnabled           = false
            });

            var byteArrayOutputStream = new MemoryStream();

            bitmap.Compress(Bitmap.CompressFormat.Png, 100, byteArrayOutputStream);
            var byteArray = byteArrayOutputStream.ToArray();

            var imageData = Convert.ToBase64String(byteArray);

            var responses = vision.Images.Annotate(
                new BatchAnnotateImagesRequest()
            {
                Requests = new[] {
                    new AnnotateImageRequest()
                    {
                        Features = new [] { new Feature()
                                            {
                                                Type =
                                                    "LABEL_DETECTION"
                                            } },
                        Image = new Image()
                        {
                            Content = imageData
                        }
                    }
                }
            }).Execute();
        }
Example #27
0
        public async Task PostPolicyAcl()
        {
            var bucketName = _fixture.BucketName;
            var objectName = "places/world.txt";
            var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential;

            // Sample: PostPolicyAcl
            // Create a signed post policy which can be used to upload a specific object and
            // expires in 10 seconds after creation.
            // It also sets a starts-with condition on the acl form element, that should be met
            // by the actual form used for posting.
            UrlSigner urlSigner = UrlSigner
                                  .FromServiceAccountCredential(credential);

            UrlSigner.Options options = UrlSigner.Options
                                        .FromDuration(TimeSpan.FromHours(1))
                                        .WithSigningVersion(SigningVersion.V4)
                                        .WithScheme("https");
            UrlSigner.PostPolicy postPolicy = UrlSigner.PostPolicy.ForBucketAndKey(bucketName, objectName);
            postPolicy.SetStartsWith(UrlSigner.PostPolicyStandardElement.Acl, "public");

            UrlSigner.SignedPostPolicy signedPostPolicy = await urlSigner.SignAsync(postPolicy, options);

            // Create an HTML form including all the fields in the signed post policy.
            StringBuilder form = new StringBuilder();

            form.AppendLine($"<form action=\"{signedPostPolicy.PostUrl}\" method=\"post\" enctype=\"multipart/form-data\">");
            foreach (var field in signedPostPolicy.Fields)
            {
                form.AppendLine($"<input type=\"hidden\" name=\"{field.Key}\" value=\"{field.Value}\">");
            }
            // Include also an acl element with a value that meets the condition set in the policy.
            form.AppendLine("<input type=\"hidden\" name=\"acl\" value=\"public-read\">");
            // Include the file element. It should always be the last element in the form.
            form.AppendLine("<input name=\"file\" type=\"file\">");
            form.AppendLine("<input type=\"submit\" value=\"Upload\">");
            form.AppendLine("</form>");

            // You can now save the form to file and serve it as static content
            // or send it as the response to a request made to your application.
            File.WriteAllText("PostPolicyAcl.html", form.ToString());
            //// End sample

            Assert.Contains(signedPostPolicy.PostUrl.ToString(), form.ToString());
            File.Delete("PostPolicyAcl.html");
        }
Example #28
0
        /// <summary>
        /// Asynchronously creates a new <see cref="StorageClient"/> from the default application credentials.
        /// </summary>
        /// <remarks>
        /// The application credentials are available to developers by running <c>gcloud auth</c> from the
        /// command line, and are available automatically on Google Cloud Platform hosts.
        /// </remarks>
        /// <param name="applicationName">The name of the application to create a client for. Must not be null.</param>
        /// <returns>A client configured with the application-default credentials.</returns>
        public static async Task <StorageClient> FromApplicationCredentials(string applicationName)
        {
            Preconditions.CheckNotNull(applicationName, nameof(applicationName));
            var credentials = await GoogleCredential.GetApplicationDefaultAsync();

            if (credentials.IsCreateScopedRequired)
            {
                credentials = credentials.CreateScoped(StorageService.Scope.DevstorageFullControl);
            }
            var initializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials,
                ApplicationName       = applicationName,
            };

            return(new StorageClient(initializer));
        }
        /// <summary>
        /// Obtains channel credentials asynchronously. Override this method in a concrete builder type if more
        /// credential mechanisms are supported.
        /// </summary>
        protected async virtual Task <ChannelCredentials> GetChannelCredentialsAsync(CancellationToken cancellationToken)
        {
            if (ChannelCredentials != null)
            {
                return(ChannelCredentials);
            }
            if (TokenAccessMethod != null)
            {
                return(new DelegatedTokenAccess(TokenAccessMethod).ToChannelCredentials());
            }
            GoogleCredential unscoped =
                CredentialsPath != null?GoogleCredential.FromFile(CredentialsPath) :   // TODO: Use an async method when one is available
                    JsonCredentials != null?GoogleCredential.FromJson(JsonCredentials) :
                        await GoogleCredential.GetApplicationDefaultAsync().ConfigureAwait(false);

            return(unscoped.CreateScoped(Scopes ?? GetDefaultScopes()).ToChannelCredentials());
        }
Example #30
0
        public static async Task RunPerRpcCredsAsync(IChannelWrapper channel, ClientOptions options)
        {
            var client     = CreateClient <TestService.TestServiceClient>(channel);
            var oauthScope = options.OAuthScope !;

            var googleCredential = await GoogleCredential.GetApplicationDefaultAsync();

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

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

            Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username);
        }