Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            var           target_audience = "https://example.com";
            GoogleIDToken gid             = new GoogleIDToken();

            string CREDENTIAL_FILE_JSON = "/path/to/service_account.json";
            ServiceAccountCredential svc_credential;

            using (var stream = new FileStream(CREDENTIAL_FILE_JSON, FileMode.Open, FileAccess.Read))
            {
                svc_credential = ServiceAccountCredential.FromServiceAccountData(stream);
            }

            // For ServiceAccount
            string id_token = gid.GetIDTokenFromServiceAccount(svc_credential, target_audience);

            // For Compute Engine
            //string id_token = gid.GetIDTokenFromComputeEngine(target_audience);

            Console.WriteLine("ID Token: " + id_token);
            gid.VerifyIDToken(id_token).Wait();

            string url = "https://example.com";

            gid.MakeAuthenticatedRequest(id_token, url);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Authenticates using the client id and credentials, then fetches
        /// the uri.
        /// </summary>
        /// <param name="iapClientId">The client id observed on
        /// https://console.cloud.google.com/apis/credentials. </param>
        /// <param name="credentialsFilePath">Path to the credentials .json file
        /// downloaded from https://console.cloud.google.com/apis/credentials.
        /// </param>
        /// <param name="uri">HTTP uri to fetch.</param>
        /// <returns>The http response body as a string.</returns>
        public async Task <string> InvokeRequestAsync(string iapClientId, string credentialsFilePath, string uri)
        {
            // Read credentials from the credentials .json file.
            ServiceAccountCredential saCredential;

            using (var fs = new FileStream(credentialsFilePath, FileMode.Open, FileAccess.Read))
            {
                saCredential = ServiceAccountCredential.FromServiceAccountData(fs);
            }

            // Request an OIDC token for the Cloud IAP-secured client ID.
            OidcToken oidcToken = await saCredential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(iapClientId)).ConfigureAwait(false);

            // Always request the string token from the OIDC token, the OIDC token will refresh the string token if it expires.
            string token = await oidcToken.GetAccessTokenAsync().ConfigureAwait(false);

            // Include the OIDC token in an Authorization: Bearer header to
            // IAP-secured resource
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                string response = await httpClient.GetStringAsync(uri).ConfigureAwait(false);

                return(response);
            }
        }
Ejemplo n.º 3
0
        private IKeyManagement GetGoogleCloudKeyManagment()
        {
            var location        = Configuration.GetValue <string>("KeyManagement:GoogleKms:Location");
            var keyRingName     = Configuration.GetValue <string>("KeyManagement:GoogleKms:KeyRingName");
            var protectionLevel = Configuration.GetValue <string>("KeyManagement:GoogleKms:ProtectionLevel");
            var credentialsPath = Configuration.GetValue <string>("KeyManagement:GoogleKms:CredentialsPath");

            var serviceAccountCredential = ServiceAccountCredential.FromServiceAccountData(File.OpenRead(credentialsPath));
            var credentials = GoogleCredential.FromServiceAccountCredential(serviceAccountCredential);

            if (credentials.IsCreateScopedRequired)
            {
                credentials = credentials.CreateScoped(new[]
                {
                    CloudKMSService.Scope.CloudPlatform
                });
            }

            var kmsService = new CloudKMSService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials,
                GZipEnabled           = true
            });


            return(new GoogleCloudKeyManagment(
                       kmsService,
                       serviceAccountCredential.ProjectId,
                       keyRingName,
                       location,
                       protectionLevel));
        }
Ejemplo n.º 4
0
        private static async Task ListObjectsAsync()
        {
            try
            {
                Console.WriteLine("Listing objects stored in a bucket");
                var    roleArn = "arn:aws:iam::291738886548:role/s3webreaderrole";
                string CREDENTIAL_FILE_JSON = "/path/to/svc.json";


                // Get the idtoken as string and use it in a standard credential
                // var targetAudience = "https://sts.amazonaws.com/";
                // var idToken = await getGoogleOIDCToken(targetAudience, CREDENTIAL_FILE_JSON);
                // var rawIdToken = await idToken.GetAccessTokenAsync().ConfigureAwait(false);
                // SessionAWSCredentials tempCredentials = await getTemporaryCredentialsAsync(rawIdToken, roleArn, "testsession");
                // Console.WriteLine(tempCredentials.GetCredentials().Token);
                // using (s3Client = new AmazonS3Client(tempCredentials, bucketRegion))

                // or create a usable GoogleCredential to wrap that
                ServiceAccountCredential saCredential;
                using (var fs = new FileStream(CREDENTIAL_FILE_JSON, FileMode.Open, FileAccess.Read))
                {
                    saCredential = ServiceAccountCredential.FromServiceAccountData(fs);
                }
                var getSessionTokenRequest = new AssumeRoleWithWebIdentityRequest
                {
                    RoleSessionName = "testsession",
                    RoleArn         = roleArn
                };
                var cc = new GoogleCompatCredentials(saCredential, "https://sts.amazonaws.com/", getSessionTokenRequest);
                using (s3Client = new AmazonS3Client(cc, bucketRegion))

                //  *****************
                {
                    var listObjectRequest = new ListObjectsRequest
                    {
                        BucketName = bucketName
                    };
                    ListObjectsResponse response = await s3Client.ListObjectsAsync(listObjectRequest);

                    List <S3Object> objects = response.S3Objects;
                    foreach (S3Object o in objects)
                    {
                        Console.WriteLine("Object  = {0}", o.Key);
                    }
                }
            }
            catch (AmazonS3Exception s3Exception)
            {
                Console.WriteLine(s3Exception.Message, s3Exception.InnerException);
            }
            catch (AmazonSecurityTokenServiceException stsException)
            {
                Console.WriteLine(stsException.Message, stsException.InnerException);
            }
        }
Ejemplo n.º 5
0
        public static void AuthorizeSerivceAcc()
        {
            ServiceAccountCredential credential;

            credential = ServiceAccountCredential
                         .FromServiceAccountData(
                new IO.FileStream(
                    "service_account_key.json",
                    IO.FileMode.Open,
                    IO.FileAccess.Read
                    ));

            accessToken = credential.GetAccessTokenForRequestAsync("https://www.googleapis.com/auth/drive").Result;
        }
Ejemplo n.º 6
0
        public async Task <FileURLOutputDTO> GetFileUrl(string filename)
        {
            using (Stream stream = new FileStream(this.keypath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var       credential = ServiceAccountCredential.FromServiceAccountData(stream);
                UrlSigner urlSigner  = UrlSigner.FromServiceAccountCredential(credential);
                var       url        = await urlSigner.SignAsync(this.bucketName, filename, TimeSpan.FromHours(1), HttpMethod.Get);

                return(new FileURLOutputDTO()
                {
                    Url = url
                });
            }
        }
Ejemplo n.º 7
0
    public ReadSheet(string spreadsheetId, string jsonPath)
    {
        this.spreadsheetId = spreadsheetId;
        this.jsonPath      = jsonPath;

        string fullJsonPath = Application.dataPath + jsonPath;

        Stream jsonCreds = (Stream)File.Open(fullJsonPath, FileMode.Open);

        ServiceAccountCredential credential = ServiceAccountCredential.FromServiceAccountData(jsonCreds);

        service = new SheetsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
        });
    }
Ejemplo n.º 8
0
        public Jwt()
        {
            Config config = Config.getInstance();

            this.aud     = config.getAudience();
            this.iat     = (int)(System.DateTime.UtcNow - new System.DateTime(1970, 1, 1)).TotalSeconds;
            this.typ     = config.getJwtType();
            this.iss     = config.getServiceAccountEmailAddress();
            this.origins = config.getOrigins();
            this.payload = new JwtPayload();
            string serviceAccountFile = config.getServiceAccountFile();

            using (FileStream fs = new FileStream(serviceAccountFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                this.credential = ServiceAccountCredential.FromServiceAccountData(fs);
            }
        }
        public ServiceAccountCredential BuildCredential(GoogleServiceParameter parameters)
        {
            ServiceAccountCredential credential;
            var credentialParameters = NewtonsoftJsonSerializer.Instance.Deserialize <JsonCredentialParameters>(File.ReadAllText(parameters.AccountFilePath));

            using (var stream = new FileStream(parameters.AccountFilePath, FileMode.Open, FileAccess.Read))
            {
                credential = ServiceAccountCredential.FromServiceAccountData(stream);
            }
            var credentialforuser = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(parameters.AccountEmail)
            {
                Scopes = parameters.ApiScopes,
                User   = string.IsNullOrEmpty(parameters.UserToImpersonate) ? parameters.AccountAdminUser : parameters.UserToImpersonate,
                Key    = credential.Key
            }.FromPrivateKey(credentialParameters.PrivateKey));

            return(credentialforuser);
        }
Ejemplo n.º 10
0
        public static async Task <OidcToken> getGoogleOIDCToken(string targetAudience, string credentialsFilePath)
        {
            //GoogleCredential gCredential;
            ServiceAccountCredential saCredential;

            //ComputeCredential cCredential;

            using (var fs = new FileStream(credentialsFilePath, FileMode.Open, FileAccess.Read))
            {
                saCredential = ServiceAccountCredential.FromServiceAccountData(fs);
            }

            //cCredential = new ComputeCredential();
            //gCredential = await GoogleCredential.GetApplicationDefaultAsync();
            OidcToken oidcToken = await saCredential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(targetAudience).WithTokenFormat(OidcTokenFormat.Standard)).ConfigureAwait(false);

            return(oidcToken);
        }
Ejemplo n.º 11
0
        public GoogleStorageService(string name, IOptions <GoogleSettings> googleSettings, bool allowDirectDownload, bool allowDirectUpload, ILogger <StorageServiceProvider> logger)
        {
            Type                   = StorageServiceProvider.GOOGLE_STORAGE;
            Name                   = name;
            GoogleSettings         = googleSettings.Value;
            SupportsDirectDownload = false;
            AllowDirectDownload    = allowDirectDownload;
            SupportsDirectUpload   = false;
            AllowDirectUpload      = allowDirectUpload;
            _logger                = logger;

            // use a tool like this to escape the Google Service Account Credentials JSON file so you can add it to appsettings.json:
            // https://www.freeformatter.com/json-escape.html
            var sacByteArray = Encoding.UTF8.GetBytes(GoogleSettings.ServiceAccountCredential);
            var sacStream    = new MemoryStream(sacByteArray);
            var credential   = GoogleCredential.FromServiceAccountCredential(ServiceAccountCredential.FromServiceAccountData(sacStream));

            _googleClient = StorageClient.Create(credential);
        }
Ejemplo n.º 12
0
        public async Task <string> Run(string targetAudience, string credentialsFilePath, string uri)
        {
            ServiceAccountCredential saCredential;

            using (var fs = new FileStream(credentialsFilePath, FileMode.Open, FileAccess.Read))
            {
                saCredential = ServiceAccountCredential.FromServiceAccountData(fs);
            }
            OidcToken oidcToken = await saCredential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(targetAudience).WithTokenFormat(OidcTokenFormat.Standard)).ConfigureAwait(false);

            string token = await oidcToken.GetAccessTokenAsync().ConfigureAwait(false);

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                string response = await httpClient.GetStringAsync(uri).ConfigureAwait(false);

                Console.WriteLine(response);
                return(response);
            }
        }
        private void InitGoogleAPI()
        {
            ResourceManager RM = new ResourceManager("GoogleAPI.Properties.Resources", Assembly.GetExecutingAssembly());

            byte[] credentialsFile = (byte[])RM.GetObject("credentials");
            string json            = Encoding.UTF8.GetString(credentialsFile);

            GoogleCredential credential = GoogleCredential.FromJson(json);

            Storage = StorageClient.Create(credential);

            string path = System.IO.Path.GetTempPath() + "credentials.json";

            File.WriteAllBytes(path, Properties.Resources.credentials);

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
            ImageAnnotator = ImageAnnotatorClient.Create();

            ServiceAccountCredential serviceAccountCredential = ServiceAccountCredential.FromServiceAccountData(new MemoryStream(credentialsFile));

            UrlSigner = UrlSigner.FromServiceAccountCredential(serviceAccountCredential);
        }
        public GoogleCloudKeyManagmentTests()
        {
            mConfiguration = new ConfigurationBuilder()
                             .AddJsonFile("settings.json")
                             .AddEnvironmentVariables().Build();

            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);

            writer.Write(mConfiguration.GetValue <string>("KeyManagment:GoogleKms:Credentials"));
            writer.Flush();
            stream.Position = 0;
            var serviceAccountCredential = ServiceAccountCredential.FromServiceAccountData(stream);
            var credentials = GoogleCredential.FromServiceAccountCredential(serviceAccountCredential);

            if (credentials.IsCreateScopedRequired)
            {
                credentials = credentials.CreateScoped(new[]
                {
                    CloudKMSService.Scope.CloudPlatform
                });
            }

            mCloudKmsService = new CloudKMSService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials,
                GZipEnabled           = true
            });
            var location        = mConfiguration.GetValue <string>("KeyManagment:GoogleKms:Location");
            var keyRingName     = mConfiguration.GetValue <string>("KeyManagment:GoogleKms:KeyRingName");
            var protectionLevel = mConfiguration.GetValue <string>("KeyManagment:GoogleKms:ProtectionLevel");

            mGoogleCloudKeyManagement = new GoogleCloudKeyManagment(
                mCloudKmsService,
                serviceAccountCredential.ProjectId,
                keyRingName,
                location,
                protectionLevel);
        }
Ejemplo n.º 15
0
        public async Task <string> Run(string targetAudience, string credentialsFilePath, string uri)
        {
            ServiceAccountCredential saCredential;

            using (var fs = new FileStream(credentialsFilePath, FileMode.Open, FileAccess.Read))
            {
                saCredential = ServiceAccountCredential.FromServiceAccountData(fs);
            }
            OidcToken oidcToken = await saCredential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(targetAudience).WithTokenFormat(OidcTokenFormat.Standard)).ConfigureAwait(false);

            string token = await oidcToken.GetAccessTokenAsync().ConfigureAwait(false);

            // the following snippet verifies an id token.
            // this step is done on the  receiving end of the oidc endpoint
            // adding this step in here as just as a demo on how to do this
            //var options = SignedTokenVerificationOptions.Default;
            SignedTokenVerificationOptions options = new SignedTokenVerificationOptions
            {
                IssuedAtClockTolerance = TimeSpan.FromMinutes(1),
                ExpiryClockTolerance   = TimeSpan.FromMinutes(1),
                TrustedAudiences       = { targetAudience },
                CertificatesUrl        = "https://www.googleapis.com/oauth2/v3/certs" // default value
            };
            var payload = await JsonWebSignature.VerifySignedTokenAsync(token, options);

            Console.WriteLine("Verified with audience " + payload.Audience);
            // end verification

            // use the token
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                string response = await httpClient.GetStringAsync(uri).ConfigureAwait(false);

                Console.WriteLine(response);
                return(response);
            }
        }
        /// <summary>
        /// Authenticates using the client id and credentials, then fetches
        /// the uri.
        /// </summary>
        /// <param name="iapClientId">The client id observed on
        /// https://console.cloud.google.com/apis/credentials.</param>
        /// <param name="credentialsFilePath">Path to the credentials .json file
        /// download from https://console.cloud.google.com/apis/credentials.
        /// </param>
        /// <param name="uri">HTTP uri to fetch.</param>
        /// <returns>The http response body as a string.</returns>
        public static string InvokeRequest(string iapClientId,
                                           string credentialsFilePath, string uri)
        {
            // Read credentials from the credentials .json file.
            ServiceAccountCredential saCredential;

            using (var fs = new FileStream(credentialsFilePath,
                                           FileMode.Open, FileAccess.Read))
            {
                saCredential = ServiceAccountCredential
                               .FromServiceAccountData(fs);
            }

            // Generate a JWT signed with the service account's private key
            // containing a special "target_audience" claim.
            var jwtBasedAccessToken =
                CreateAccessToken(saCredential, iapClientId);

            // Request an OIDC token for the Cloud IAP-secured client ID.
            var req = new GoogleAssertionTokenRequest()
            {
                Assertion = jwtBasedAccessToken
            };
            var result = req.ExecuteAsync(saCredential.HttpClient,
                                          saCredential.TokenServerUrl, CancellationToken.None,
                                          saCredential.Clock).Result;
            string token = result.IdToken;

            // Include the OIDC token in an Authorization: Bearer header to
            // IAP-secured resource
            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", token);
            string response = httpClient.GetStringAsync(uri).Result;

            return(response);
        }
Ejemplo n.º 17
0
        public async Task SendEvent(IHiarcEvent theEvent)
        {
            try
            {
                var serializedEvent = JsonSerializer.Serialize(theEvent);

                var topicName      = new TopicName(_pubSubSettings.ProjectId, _pubSubSettings.Topic);
                var sacByteArray   = Encoding.UTF8.GetBytes(_pubSubSettings.ServiceAccountCredential);
                var sacStream      = new MemoryStream(sacByteArray);
                var credential     = GoogleCredential.FromServiceAccountCredential(ServiceAccountCredential.FromServiceAccountData(sacStream));
                var createSettings = new ClientCreationSettings(credentials: credential.ToChannelCredentials());
                var publisher      = await CreateAsync(topicName, clientCreationSettings : createSettings);

                var messageId = await publisher.PublishAsync(serializedEvent);

                await publisher.ShutdownAsync(TimeSpan.FromSeconds(10));

                _logger.LogDebug($"Successfully sent event '{theEvent.Event}' to '{this.Name}'. Payload: {serializedEvent}");
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to send event '{theEvent.Event}' to '{this.Name}'. Exception: {ex.Message}");
            }
        }
Ejemplo n.º 18
0
        private static void ServiceAccounts(string credentialsJson, string userEmail)
        {
            LoginAsServiceAccountWithJson(credentialsJson);

            IList <ServiceAccountKey> serviceAccountKeys = ListKeysOfServiceAccount(userEmail);

            ServiceAccountKey newKey = CreateKeyOfServiceAccount(userEmail);

            // Call the translate API with the new key.
            byte[] jsonKey       = Convert.FromBase64String(newKey.PrivateKeyData);
            Stream jsonKeyStream = new MemoryStream(jsonKey);
            ServiceAccountCredential credential = ServiceAccountCredential
                                                  .FromServiceAccountData(jsonKeyStream);
            GoogleCredential googleCredential = GoogleCredential
                                                .FromServiceAccountCredential(credential);
            var client   = TranslationClient.Create(googleCredential);
            var response = client.TranslateText("Hello World", "ru");

            Console.WriteLine(response.TranslatedText);

            //DeleteKeyOfServiceAccount(newKey);

            // LoginWithServiceAccountKey(newKey, credentialsJson);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Creates a new <see cref="UrlSigner"/> instance for a service account.
 /// </summary>
 /// <param name="credentialData">The stream from which to read the JSON key data for a service account. Must not be null.</param>
 /// <exception cref="InvalidOperationException">
 /// The <paramref name="credentialData"/> does not contain valid JSON service account key data.
 /// </exception>
 public static UrlSigner FromServiceAccountData(Stream credentialData)
 {
     GaxPreconditions.CheckNotNull(credentialData, nameof(credentialData));
     return(UrlSigner.FromServiceAccountCredential(ServiceAccountCredential.FromServiceAccountData(credentialData)));
 }