public async Task RefreshesOidcToken()
        {
            // A little bit after the tokens returned from OidcTokenFakes were issued.
            var clock          = new MockClock(new DateTime(2020, 5, 13, 15, 0, 0, 0, DateTimeKind.Utc));
            var messageHandler = new OidcTokenResponseSuccessMessageHandler();
            var initializer    = new ServiceAccountCredential.Initializer("MyId", "http://will.be.ignored")
            {
                Clock             = clock,
                ProjectId         = "a_project_id",
                HttpClientFactory = new MockHttpClientFactory(messageHandler)
            };
            var credential = new ServiceAccountCredential(initializer.FromPrivateKey(PrivateKey));

            var oidcToken = await credential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience("audience"));

            var signedToken = SignedToken <Header, Payload> .FromSignedToken(await oidcToken.GetAccessTokenAsync());

            Assert.Equal("https://first_call.test", signedToken.Payload.Audience);
            // Move the clock so that the token expires.
            clock.UtcNow = clock.UtcNow.AddHours(2);
            signedToken  = SignedToken <Header, Payload> .FromSignedToken(await oidcToken.GetAccessTokenAsync());

            Assert.Equal("https://subsequent_calls.test", signedToken.Payload.Audience);
            // Two calls, because the second time we tried to get the token, the first one had expired.
            Assert.Equal(2, messageHandler.Calls);
        }
Ejemplo n.º 2
0
        public BaseClientService.Initializer GetInitializer(string accountName = null, params string[] scopes)
        {
            var credPath = _google.CredentiaPath;

            if (string.IsNullOrWhiteSpace(accountName))
            {
                accountName = _google.DefaultAccountName;
            }

            var originCredential =
                (ServiceAccountCredential)GoogleCredential.FromFile(credPath)
                .UnderlyingCredential;

            var initializer = new ServiceAccountCredential.Initializer(originCredential.Id)
            {
                User   = accountName,
                Key    = originCredential.Key,
                Scopes = scopes
            };

            var credential = new ServiceAccountCredential(initializer);

            return(new BaseClientService.Initializer
            {
                ApplicationName = "MyPortal",
                HttpClientInitializer = credential
            });
        }
Ejemplo n.º 3
0
        private GmailService GetService(string user, TimeSpan timeout)
        {
            lock (this.cache)
            {
                if (!this.cache.Contains(user))
                {
                    ServiceAccountCredential.Initializer initializerInstance = new ServiceAccountCredential.Initializer(this.serviceAccountID)
                    {
                        User   = user,
                        Scopes = this.scopes
                    }.FromCertificate(this.x509Certificate);

                    GmailService x = new GmailService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer           = new ServiceAccountCredential(initializerInstance),
                        ApplicationName                 = "LithnetGoogleAppsLibrary",
                        GZipEnabled                     = !Settings.DisableGzip,
                        Serializer                      = new GoogleJsonSerializer(),
                        DefaultExponentialBackOffPolicy = ExponentialBackOffPolicy.None,
                    });

                    x.HttpClient.Timeout = timeout;
                    this.cache.Add(user, x);

                    if (this.cache.Count > CacheSize)
                    {
                        this.cache.RemoveAt(0);
                    }
                }

                return((GmailService)this.cache[user]);
            }
        }
Ejemplo n.º 4
0
        private ServiceAccountCredential GetAccountCredential(byte[] p12key, string password, string serviceAccountEmail)
        {
            var certificate = new X509Certificate2(p12key, password, X509KeyStorageFlags.Exportable);

            var serviceAccountCredentialInitializer =
                new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[]
                {
                    "https://spreadsheets.google.com/feeds",
                    DriveService.Scope.Drive
                }
            }.FromCertificate(certificate);

            var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);

            Wait.UntilNoException(() =>
            {
                if (!credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result)
                {
                    throw new InvalidOperationException("Access token request failed.");
                }
            }, 60 * 1000);
            return(credential);
        }
Ejemplo n.º 5
0
        public BaseClientService.Initializer GetInitializer(string accountName = null)
        {
            var credPath = _config.GetValue <string>("GSuiteIntegration:CredentialPath");

            if (string.IsNullOrWhiteSpace(accountName))
            {
                accountName = _config.GetValue <string>("GSuiteIntegration:DefaultAccountName");
            }

            var originCredential =
                (ServiceAccountCredential)GoogleCredential.FromFile(credPath)
                .UnderlyingCredential;

            var initializer = new ServiceAccountCredential.Initializer(originCredential.Id)
            {
                User   = accountName,
                Key    = originCredential.Key,
                Scopes = _scopes
            };

            var credential = new ServiceAccountCredential(initializer);

            return(new BaseClientService.Initializer
            {
                ApplicationName = "MyPortal",
                HttpClientInitializer = credential
            });
        }
Ejemplo n.º 6
0
        private static SheetsService UserCredential()
        {
            try
            {
                ServiceAccountCredential credential1;
                string[] Scopes = { SheetsService.Scope.Spreadsheets };
                string   serviceAccountEmail = "*****@*****.**";
                string   jsonfile            = "trackingNewData.json";
                using (Stream stream = new FileStream(@jsonfile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    credential1 = (ServiceAccountCredential)
                                  GoogleCredential.FromStream(stream).UnderlyingCredential;

                    var initializer = new ServiceAccountCredential.Initializer(credential1.Id)
                    {
                        User   = serviceAccountEmail,
                        Key    = credential1.Key,
                        Scopes = Scopes
                    };
                    credential1 = new ServiceAccountCredential(initializer);
                }
                var service = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential1,
                    ApplicationName       = "",
                });
                return(service);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }
        }
        public async Task FetchesOidcToken()
        {
            // A little bit after the tokens returned from OidcTokenFakes were issued.
            var clock          = new MockClock(new DateTime(2020, 5, 13, 15, 0, 0, 0, DateTimeKind.Utc));
            var messageHandler = new OidcTokenResponseSuccessMessageHandler();
            var initializer    = new ServiceAccountCredential.Initializer("MyId", "http://will.be.ignored")
            {
                Clock             = clock,
                ProjectId         = "a_project_id",
                HttpClientFactory = new MockHttpClientFactory(messageHandler)
            };
            var credential = new ServiceAccountCredential(initializer.FromPrivateKey(PrivateKey));

            // The fake Oidc server returns valid tokens (expired in the real world for safety)
            // but with a set audience that lets us know if the token was refreshed or not.
            var oidcToken = await credential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience("will.be.ignored"));

            var signedToken = SignedToken <Header, Payload> .FromSignedToken(await oidcToken.GetAccessTokenAsync());

            Assert.Equal("https://first_call.test", signedToken.Payload.Audience);
            // Move the clock some but not enough that the token expires.
            clock.UtcNow = clock.UtcNow.AddMinutes(20);
            signedToken  = SignedToken <Header, Payload> .FromSignedToken(await oidcToken.GetAccessTokenAsync());

            Assert.Equal("https://first_call.test", signedToken.Payload.Audience);
            // Only the first call should have resulted in a request. The second time the token hadn't expired.
            Assert.Equal(1, messageHandler.Calls);
        }
Ejemplo n.º 8
0
        public async Task JwtCache_Size()
        {
            var clock = new MockClock {
                UtcNow = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc)
            };
            var initializer = new ServiceAccountCredential.Initializer("some-id")
            {
                Clock = clock
            }.FromPrivateKey(PrivateKey);
            var cred = new ServiceAccountCredential(initializer);

            Assert.False(cred.HasScopes); // Must be false for the remainder of this test to be valid.
            // Check JWTs removed from cache once cache fills up.
            var jwt0 = await cred.GetAccessTokenForRequestAsync("uri0");

            for (int i = 0; i < ServiceAccountCredential.JwtCacheMaxSize; i++)
            {
                await cred.GetAccessTokenForRequestAsync($"uri{i}");

                // Check jwt is retrieved from cache.
                var jwt0Cached = await cred.GetAccessTokenForRequestAsync("uri0");

                Assert.Same(jwt0, jwt0Cached);
            }
            // Add one more JWT to cache that should remove jwt0 from the cache.
            await cred.GetAccessTokenForRequestAsync("uri_too_much");

            var jwt0Uncached = await cred.GetAccessTokenForRequestAsync("uri0");

            Assert.NotSame(jwt0, jwt0Uncached);
        }
        private ServiceAccountCredential getServiceAccountCredential(String pathToJsonFile,
                                                                     String emailToImpersonate)
        {
            // Load and deserialize credential parameters from the specified JSON file.
            JsonCredentialParameters parameters;

            using (Stream json = new FileStream(pathToJsonFile, FileMode.Open, FileAccess.Read)) {
                parameters = NewtonsoftJsonSerializer.Instance.Deserialize <JsonCredentialParameters>(json);
            }

            // Create a credential initializer with the correct scopes.
            ServiceAccountCredential.Initializer initializer =
                new ServiceAccountCredential.Initializer(parameters.ClientEmail)
            {
                Scopes = OAuthScopes
            };

            // Configure impersonation (if applicable).
            if (!String.IsNullOrEmpty(emailToImpersonate))
            {
                initializer.User = emailToImpersonate;
            }

            // Create a service account credential object using the deserialized private key.
            ServiceAccountCredential credential =
                new ServiceAccountCredential(initializer.FromPrivateKey(parameters.PrivateKey));

            return(credential);
        }
Ejemplo n.º 10
0
        private ServiceAccountCredential CreateServiceAccountCredential(IHttpClientFactory httpClientFactory, IFcmClientSettings settings)
        {
            var serviceAccountCredential = GoogleCredential.FromJson(settings.Credentials)
                                           // We need the Messaging Scope:
                                           .CreateScoped("https://www.googleapis.com/auth/firebase.messaging")
                                           // Cast to the ServiceAccountCredential:
                                           .UnderlyingCredential as ServiceAccountCredential;

            if (serviceAccountCredential == null)
            {
                throw new Exception($"Error creating ServiceAccountCredential from JSON File {settings.Credentials}");
            }

            var initializer = new ServiceAccountCredential.Initializer(serviceAccountCredential.Id, serviceAccountCredential.TokenServerUrl)
            {
                User              = serviceAccountCredential.User,
                AccessMethod      = serviceAccountCredential.AccessMethod,
                Clock             = serviceAccountCredential.Clock,
                Key               = serviceAccountCredential.Key,
                Scopes            = serviceAccountCredential.Scopes,
                HttpClientFactory = httpClientFactory
            };

            return(new ServiceAccountCredential(initializer));
        }
Ejemplo n.º 11
0
        public void Foo5()
        {
            //GoogleCredential credential;
            var          keyFilePath = "../../Test/SgxProject-c88a95424dbd.p12";
            const string user        = "******";
            var          certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);

            var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(user)
            {
                //Scopes = new[] { SheetsService.Scope.Drive, SheetsService.Scope.Spreadsheets, DriveService.Scope.Drive, "https://docs.google.com/feeds", "https://spreadsheets.google.com/feeds" }
                Scopes = new[] { SheetsService.Scope.Drive, SheetsService.Scope.Spreadsheets, "https://docs.google.com/feeds", "https://spreadsheets.google.com/feeds" }
            }.FromCertificate(certificate);

            var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);

            if (!credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result)
            {
                throw new InvalidOperationException("Access token request failed.");
            }



            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });


            // Define request parameters.
            String spreadsheetId = "1u3wBMRwj09MvRaXd817p2zcqwTmRgjeYKYNsUKMwsnc";//Demo2
            //String range = "Sheet1!D5";  // single cell D5
            String range = "Sheet1!A5";
            //String myNewCellValue = "Tom";
            ValueRange valueRange = new ValueRange();

            //valueRange.Range = "Sheet1!A5";
            valueRange.Values = new List <IList <object> > {
                new List <object> {
                    "A", "B"
                }
            };                                                                            //{ new List<object>{ 1, 2, 3 } , new List<object> { 4, 5, 6 } };
            //IList<IList<object>> xx = new List<IList<object>>();
            //xx.Add(new List<object> { "test" });
            //valueRange.Values = xx;

            var request = service.Spreadsheets.Values.Update(valueRange, spreadsheetId, range);

            request.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
            //var request = service.Spreadsheets.Values.Get(spreadsheetId, range);

            // Prints the names and majors of students in a sample spreadsheet:
            // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
            var response = request.Execute();

            //IList<IList<Object>> values = response..Values;
            //Console.WriteLine(values);
        }
Ejemplo n.º 12
0
        public void Pkcs8Decoding_FromPrivateKey()
        {
            // This is a service credential, as downloaded from the Cloud Console on 2016-12-08
            string dummyServiceAccountCredentialFileContents = @"
{
""type"": ""service_account"",
""private_key_id"": ""71bb487f3414f923196c5c433cf20a8c0f689562"",
""private_key"": ""-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDQvitimRPWE2YM
tOADu3jb89UQmqZz8ao6NFoAjYiYDdg/6UBUTscQwGb6rIvllMtcT6BdS4rMKUwv
kSQFbO14gi7FiZBj4eJKveObVnt9RPxqT1txBieEPFtgJalh0GpyCo5GUmadgqe+
89ZF+VQBFE2hMoZhBny/FDba2/qDIk1GmksdXjC67ZI0EYRCGI71eXjOpQX/wOJs
tosMQRSTHjPKhZKvZTtjksMRWm8SlQoyORZKXsV6OGKztOieIvncKoX3lrkSupax
J+v0yYQJIF2uTFDbbCDL86bgUJ7TyZJ9X1AvrnHGNWp+QzQBDbTCMpZCuY81ARdu
BHeacqR3AgMBAAECggEAK7Cx+fgaO8Nhp6UwAff6KudVIB2OW1QokfglIlp9TX4Q
VggnC75VUf9DTpJQ0aOcEN0lroFCMssuBAK37F7JMWDmEzhgvVco+wXVnsyyGh0X
S9UCSZzFJptPcMdRNYTe0rG856EVk0AmhgQZRBoUaAls2iFuGN63u3KqrJJAU7O4
MPofQizwNcMmiDqRV0rnU6HgmIRQ64hMMh1bnnw4I35esOXjO1O2PiwyyK0jHuVz
eBNeD0wEXNLIP4CqDsQ0DKyBPKXZW4bmFnluq4s+VvgPMczUli7Ph0bM7G1oR0LF
nZk8tSO9cZ4lLcZpY5mHg7lHzSE6oPAxrkPYoa+6IQKBgQD6I7KaUcmkQj+vOQ18
sZCA28tXqjW2cGB4ThqG2uYeHK8khhjh/Pj07TFr8Xjpz1gNr1NNBJhR9Qs/dO9N
WCXS6s0fsVz/gm8N36w7kcBe+Uo43UIt3U6xvZVG4eJYWe2B5+0sZeXzMfzGhwug
VkinOJ0CoVpGFTByPrn17O9T8QKBgQDVoi5AO7jvL3nxLQyfXy6XhkHvmnrRU5hV
eHrgO2+0TsjAHNRhGGrKTMDqCrMvJqxXbXAwNIKxPdzGCXjam4QzaXgp8+bJWHNe
UNRfbWUxVo/Mzfp4owN6oCOVN2cTrnz/doFhuT1LjDj2KK5+hY6qtleH+h00XjCi
0xrTGCpG5wKBgDy0pya+jKI5lb0Pqo9FhJ1ROkM3QrvZAACSa+uoekp6iaLijG1j
+INwgRsCSmbr9CG2GBBL+i+Buc4Xse/iYaOTal6zq68y14LVcrYuRDKIa5PrVqFM
4UlPikfekBEDGhn50FyDClCAJCmGIrMx3YX/vlMiF4eEovJG+NiPPPHxAoGBANQq
qKJ0bbtmPEYQxot1HTGxTcSneDhyPEUOTYJqpQq+f9OEDkyL0msthR4rGD/Iubpu
XtARJobeeGdZuuPpNYdVxNhteZQXuyQ9RF2tqKUyYcg1/P5YbzkW15/3EPDUByIz
UFV8geqIzX1zc7EF9WWHiDDsbpq2vLjIzcg+JKabAoGAI7kuoGBdvIHne3Y3tucQ
JzcnYI3bppbhyn1dmm8jsaaWrtBvFqCb1y1MjaoL4lNi+brdd6bpV5u447GBQfG8
o3L1luXTksRPmwh5NbhXWl/ieiWc6WQL6sr8Q+vSYDKAo95zdhWJvWs+/v7NfWoF
lK1DcBvq+IFLucBdi0/9hXE=
-----END PRIVATE KEY-----"",
""client_email"": ""CLIENT_EMAIL"",
""client_id"": ""112326926692598796719""
}";

            var credentialParameters = NewtonsoftJsonSerializer.Instance.Deserialize <JsonCredentialParameters>(dummyServiceAccountCredentialFileContents);
            var initializer          = new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
            {
                Clock = new MockClock {
                    UtcNow = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                }
            };

            initializer.FromPrivateKey(credentialParameters.PrivateKey);
            var ps = initializer.Key.ExportParameters(true);

            Assert.Equal("D0BE2B629913D613660CB4E003BB78DBF3D5109AA673F1AA3A345A008D88980DD83FE940544EC710C066FAAC8BE594CB5C4FA05D4B8ACC294C2F9124056CED78822EC5899063E1E24ABDE39B567B7D44FC6A4F5B710627843C5B6025A961D06A720A8E4652669D82A7BEF3D645F95401144DA1328661067CBF1436DADBFA83224D469A4B1D5E30BAED9234118442188EF57978CEA505FFC0E26CB68B0C4114931E33CA8592AF653B6392C3115A6F12950A3239164A5EC57A3862B3B4E89E22F9DC2A85F796B912BA96B127EBF4C98409205DAE4C50DB6C20CBF3A6E0509ED3C9927D5F502FAE71C6356A7E4334010DB4C2329642B98F3501176E04779A72A477", ToHex(ps.Modulus));
            Assert.Equal("010001", ToHex(ps.Exponent));
            Assert.Equal("2BB0B1F9F81A3BC361A7A53001F7FA2AE755201D8E5B542891F825225A7D4D7E105608270BBE5551FF434E9250D1A39C10DD25AE814232CB2E0402B7EC5EC93160E6133860BD5728FB05D59ECCB21A1D174BD502499CC5269B4F70C7513584DED2B1BCE7A115934026860419441A1468096CDA216E18DEB7BB72AAAC924053B3B830FA1F422CF035C326883A91574AE753A1E0988450EB884C321D5B9E7C38237E5EB0E5E33B53B63E2C32C8AD231EE57378135E0F4C045CD2C83F80AA0EC4340CAC813CA5D95B86E616796EAB8B3E56F80F31CCD4962ECF8746CCEC6D684742C59D993CB523BD719E252DC66963998783B947CD213AA0F031AE43D8A1AFBA21", ToHex(ps.D));
            Assert.Equal("FA23B29A51C9A4423FAF390D7CB19080DBCB57AA35B67060784E1A86DAE61E1CAF248618E1FCF8F4ED316BF178E9CF580DAF534D049851F50B3F74EF4D5825D2EACD1FB15CFF826F0DDFAC3B91C05EF94A38DD422DDD4EB1BD9546E1E25859ED81E7ED2C65E5F331FCC6870BA05648A7389D02A15A461530723EB9F5ECEF53F1", ToHex(ps.P));
            Assert.Equal("D5A22E403BB8EF2F79F12D0C9F5F2E978641EF9A7AD1539855787AE03B6FB44EC8C01CD461186ACA4CC0EA0AB32F26AC576D70303482B13DDCC60978DA9B8433697829F3E6C958735E50D45F6D6531568FCCCDFA78A3037AA02395376713AE7CFF768161B93D4B8C38F628AE7E858EAAB65787FA1D345E30A2D31AD3182A46E7", ToHex(ps.Q));
            Assert.Equal("3CB4A726BE8CA23995BD0FAA8F45849D513A433742BBD90000926BEBA87A4A7A89A2E28C6D63F88370811B024A66EBF421B618104BFA2F81B9CE17B1EFE261A3936A5EB3ABAF32D782D572B62E4432886B93EB56A14CE1494F8A47DE9011031A19F9D05C830A508024298622B331DD85FFBE5322178784A2F246F8D88F3CF1F1", ToHex(ps.DP));
            Assert.Equal("D42AA8A2746DBB663C4610C68B751D31B14DC4A77838723C450E4D826AA50ABE7FD3840E4C8BD26B2D851E2B183FC8B9BA6E5ED0112686DE786759BAE3E9358755C4D86D799417BB243D445DADA8A53261C835FCFE586F3916D79FF710F0D407223350557C81EA88CD7D7373B105F565878830EC6E9AB6BCB8C8CDC83E24A69B", ToHex(ps.DQ));
            Assert.Equal("23B92EA0605DBC81E77B7637B6E710273727608DDBA696E1CA7D5D9A6F23B1A696AED06F16A09BD72D4C8DAA0BE25362F9BADD77A6E9579BB8E3B18141F1BCA372F596E5D392C44F9B087935B8575A5FE27A259CE9640BEACAFC43EBD2603280A3DE73761589BD6B3EFEFECD7D6A0594AD43701BEAF8814BB9C05D8B4FFD8571", ToHex(ps.InverseQ));
        }
Ejemplo n.º 13
0
        public static ServiceAccountCredential FromServiceAccountDataWithScopesTokenServerUrl(Stream credentialData, IEnumerable <string> scopes, string tokenServerUrl)
        {
            var parameters  = NewtonsoftJsonSerializer.Instance.Deserialize <JsonCredentialParameters>(credentialData);
            var initializer = new ServiceAccountCredential.Initializer(parameters.ClientEmail, tokenServerUrl).FromPrivateKey(parameters.PrivateKey);

            initializer.Scopes = scopes;
            return(new ServiceAccountCredential(initializer));
        }
Ejemplo n.º 14
0
        public static void Execute(IList <IList <object> > list)
        {
            //UserCredential credential;
            string assembly = Utils.AssemblyDirectory;
            string file     = "dynamosheets.json";
            //string file = "credentials.json";
            string path     = Path.GetFullPath(Path.Combine(assembly, @"..\", file));
            string credPath = Path.GetFullPath(Path.Combine(assembly, @"..\", "token.json"));

            //var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);

            ServiceAccountCredential credential;

            string[] Scopes = { SheetsService.Scope.Spreadsheets };
            string   serviceAccountEmail = "*****@*****.**";

            using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                credential = (ServiceAccountCredential)
                             GoogleCredential.FromStream(stream).UnderlyingCredential;

                var initializer = new ServiceAccountCredential.Initializer(credential.Id)
                {
                    User   = serviceAccountEmail,
                    Key    = credential.Key,
                    Scopes = Scopes
                };
                credential = new ServiceAccountCredential(initializer);
            }

            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define request parameters.
            // @todo Fetch these from a config.json file or environment variables?
            String spreadsheetId  = "1A7W8jXxCBpdluOqoOSpVATHcVtDlozI8WicGN1siYRc";
            String spreadsheetTab = "Sheet1";

            // Define the sheet range
            var rng    = string.Format("{0}!A1:A{1}", spreadsheetTab, list.Count);
            var vRange = new ValueRange
            {
                Range          = rng,
                Values         = list,
                MajorDimension = "ROWS"
            };

            // Send the request to the Google Sheets API
            var rqst = service.Spreadsheets.Values.Append(vRange, spreadsheetId, rng);

            rqst.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
            rqst.Execute();
            // @todo We need to check the request was actually sent successfully and gracefully deal with cases where the API is unavailable or a 403 forbidden occurs
        }
        public static List <SpotifyInfo> GetAllSongsFromStaticSheetVN()
        {
            try
            {
                ServiceAccountCredential credential1;
                string[] Scopes = { SheetsService.Scope.Spreadsheets };
                string   serviceAccountEmail = "*****@*****.**";
                string   jsonfile            = "trackingNewData.json";
                string   spreadsheetID       = "1k0G4J_HXLzOvaOvoUPHt8m7S-ogMxaeF53SE6ZfgXfo";
                string   range = "Danh sách nhạc tổng!A2:K";
                using (Stream stream = new FileStream(@jsonfile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    credential1 = (ServiceAccountCredential)
                                  GoogleCredential.FromStream(stream).UnderlyingCredential;

                    var initializer = new ServiceAccountCredential.Initializer(credential1.Id)
                    {
                        User   = serviceAccountEmail,
                        Key    = credential1.Key,
                        Scopes = Scopes
                    };
                    credential1 = new ServiceAccountCredential(initializer);
                }
                var serices = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential1,
                    ApplicationName       = ApplicationName,
                });
                SpreadsheetsResource.ValuesResource.GetRequest.ValueRenderOptionEnum    valueRenderOption    = (SpreadsheetsResource.ValuesResource.GetRequest.ValueRenderOptionEnum) 0;
                SpreadsheetsResource.ValuesResource.GetRequest.DateTimeRenderOptionEnum dateTimeRenderOption = (SpreadsheetsResource.ValuesResource.GetRequest.DateTimeRenderOptionEnum) 0;

                SpreadsheetsResource.ValuesResource.GetRequest request = serices.Spreadsheets.Values.Get(spreadsheetID, range);
                request.ValueRenderOption    = valueRenderOption;
                request.DateTimeRenderOption = dateTimeRenderOption;

                // To execute asynchronously in an async method, replace `request.Execute()` as shown:
                Data.ValueRange         response  = request.Execute();
                IList <IList <Object> > values    = response.Values;
                List <SpotifyInfo>      listSongs = new List <SpotifyInfo>();
                foreach (var item in values)
                {
                    if (item.Count >= 6)
                    {
                        SpotifyInfo song = new SpotifyInfo();
                        song.TrackTitle = item[4].ToString();
                        song.Artists    = item[5].ToString();
                        song.Range      = "I" + (values.IndexOf(item) + 2).ToString() + ":" + "J" + (values.IndexOf(item) + 2).ToString();
                        listSongs.Add(song);
                    }
                }
                return(listSongs);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Ejemplo n.º 16
0
        private ServiceAccountCredential GetServiceAccount()
        {
            var initializer = new ServiceAccountCredential.Initializer(_options.ClientEmail)
            {
                ProjectId = _options.ProjectId
            };

            return(new ServiceAccountCredential(initializer.FromPrivateKey(_options.PrivateKey)));
        }
Ejemplo n.º 17
0
        private IConfigurableHttpClientInitializer ServiceAccountInitializer()
        {
            var svcInit = new ServiceAccountCredential.Initializer(_config.CredentialParameters.ClientEmail)
            {
                Scopes = new[] { DriveService.Scope.Drive }
            };

            return(new ServiceAccountCredential(svcInit.FromPrivateKey(_config.CredentialParameters.PrivateKey)));
        }
Ejemplo n.º 18
0
        private ServiceAccountCredential GetCredentials()
        {
            var initializer = new ServiceAccountCredential.Initializer(configuration.GoogleClientEmail);

            initializer.Scopes = Scopes;

            var result = new ServiceAccountCredential(initializer.FromPrivateKey(configuration.GoogleClientPrivateKey));

            return(result);
        }
Ejemplo n.º 19
0
            public override GoogleCredential CreateScoped(IEnumerable <string> scopes)
            {
                var serviceAccountCredential = credential as ServiceAccountCredential;
                var initializer = new ServiceAccountCredential.Initializer(serviceAccountCredential)
                {
                    Scopes = scopes
                };

                return(new ServiceAccountGoogleCredential(new ServiceAccountCredential(initializer)));
            }
Ejemplo n.º 20
0
            public override GoogleCredential CreateWithUser(string user)
            {
                var serviceAccountCredential = credential as ServiceAccountCredential;
                var initializer = new ServiceAccountCredential.Initializer(serviceAccountCredential)
                {
                    User = user
                };

                return(new ServiceAccountGoogleCredential(new ServiceAccountCredential(initializer)));
            }
Ejemplo n.º 21
0
        public string GetCoverUrl(string userId, int bookId, string coverName)
        {
            var       coverPath   = $"{_baseBookPath}{userId}/{bookId}/{coverName}";
            var       initializer = new ServiceAccountCredential.Initializer(_googleCloudStorageSettings.Id);
            UrlSigner urlSgSigner = UrlSigner.FromServiceAccountCredential(
                new ServiceAccountCredential(initializer.FromPrivateKey(_googleCloudStorageSettings.PrivateKey)));
            string url = urlSgSigner.Sign(_googleCloudStorageSettings.BucketName, coverPath, TimeSpan.FromDays(5));

            return(url);
        }
Ejemplo n.º 22
0
        public string GetDownloadUrl(string userId, int bookId, string bookFileName)
        {
            var       bookPath    = $"{_baseBookPath}{userId}/{bookId}/{bookFileName}";
            var       initializer = new ServiceAccountCredential.Initializer(_googleCloudStorageSettings.Id);
            UrlSigner urlSgSigner = UrlSigner.FromServiceAccountCredential(
                new ServiceAccountCredential(initializer.FromPrivateKey(_googleCloudStorageSettings.PrivateKey)));
            string url = urlSgSigner.Sign(_googleCloudStorageSettings.BucketName, bookPath, TimeSpan.FromMinutes(10),
                                          HttpMethod.Get);

            return(url);
        }
Ejemplo n.º 23
0
        static void Main()
        {
            var certificate = new X509Certificate2(Key, "notasecret", X509KeyStorageFlags.Exportable);
            var initializer = new ServiceAccountCredential.Initializer(ServiceAccountEmail)
            {
                Scopes = new[] { DriveService.Scope.Drive },
                User   = ImpersonatedAccountEmail
            };
            var credential   = new ServiceAccountCredential(initializer.FromCertificate(certificate));
            var driveService = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName
            });
            // Show all files
            var list = driveService.Files.List().Execute();

            if (list.Items != null)
            {
                foreach (var fileItem in list.Items)
                {
                    Console.WriteLine(fileItem.Title + " - " + fileItem.Description);
                }
            }
            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
            // Upload a new file
            File body = new File();

            body.Title       = "whakingly.txt";
            body.Description = "A whakingly (that a new word I created just there) file thats uploaded with impersonation";
            body.MimeType    = "text/plain";
            byte[] byteArray = System.IO.File.ReadAllBytes(FileToUpload);
            var    stream    = new System.IO.MemoryStream(byteArray);

            FilesResource.InsertMediaUpload request = driveService.Files.Insert(body, stream, "text/plain");
            request.Upload();
            File file = request.ResponseBody;

            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
            // Show all files
            var list2 = driveService.Files.List().Execute();

            if (list2.Items != null)
            {
                foreach (var fileItem in list2.Items)
                {
                    Console.WriteLine(fileItem.Title + " - " + fileItem.Description);
                }
            }
            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
        }
Ejemplo n.º 24
0
        private static ServiceAccountCredential.Initializer InitializeAccount(String clientEmail)
        {
            var accountInitializer = new ServiceAccountCredential.Initializer(clientEmail)
            {
                Scopes = new List <string>
                {
                    "https://www.googleapis.com/auth/cloudprint"
                }
            };

            return(accountInitializer);
        }
Ejemplo n.º 25
0
        private static string CreateSignature(string data, ServiceAccountCredential.Initializer initializer)
        {
            // TODO: This is taken from ServiceAccountCredential. Expose this somehow so we don't need to duplicate logic.
            using (var hashAlg = SHA256.Create())
            {
                byte[] assertionHash = hashAlg.ComputeHash(Encoding.UTF8.GetBytes(data));
#if NETSTANDARD1_3
                var sigBytes = initializer.Key.SignHash(assertionHash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
#else
                const string Sha256Oig = "2.16.840.1.101.3.4.2.1";
                var          sigBytes  = initializer.Key.SignHash(assertionHash, Sha256Oig);
#endif
                return(WebUtility.UrlEncode(Convert.ToBase64String(sigBytes)));
            }
        }
Ejemplo n.º 26
0
        public ServiceAccountCredential GetCredential()
        {
            var serviceAccountEmail   = ConfigurationHelper.GetAppSettingsValue(_serviceAccountEmailPropertyName);
            var certificatePath       = ConfigurationHelper.GetAppSettingsValue(_certificatePathPropertyName);
            var certificatePassphrase = ConfigurationHelper.GetAppSettingsValue(_certificatePassphrasePropertyName);

            var certificate = new X509Certificate2(certificatePath, certificatePassphrase, X509KeyStorageFlags.Exportable);

            var credentialInitializer = new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { ShoppingContentService.Scope.Content }
            }.FromCertificate(certificate);

            return(new ServiceAccountCredential(credentialInitializer));
        }
Ejemplo n.º 27
0
        public GoogleDriveManager()
        {
            var initializer = new ServiceAccountCredential.Initializer(ConfigurationManager.AppSettings["GoogleDriveServiceAccountEmail"].ToString())
            {
                Scopes = new string[] { DriveService.Scope.Drive }
            };
            var credential = new ServiceAccountCredential(initializer.FromPrivateKey(ConfigurationManager.AppSettings["GoogleDrivePrivateKey"].ToString()));

            service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ConfigurationManager.AppSettings["GoogleDriveApplicationName"].ToString(),
            });

            service.HttpClient.Timeout = TimeSpan.FromMinutes(100);
        }
Ejemplo n.º 28
0
        private ServiceAccountCredential GetServiceAccountCredential()
        {
            using (Stream stream = new FileStream("configs/service_account_secret.json", FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var credential = (ServiceAccountCredential)
                                 GoogleCredential.FromStream(stream).UnderlyingCredential;

                var initializer = new ServiceAccountCredential.Initializer(credential.Id)
                {
                    User   = serviceAccount,
                    Key    = credential.Key,
                    Scopes = scopes
                };
                return(new ServiceAccountCredential(initializer));
            }
        }
Ejemplo n.º 29
0
        private static void Main(string[] args)
        {
            // See the README.md for details of these fields.
            // Retrieved from https://console.developers.google.com
            var ServiceKeyFilePath = "PATH TO JSON KEY FILE HERE";

            // Name of the buyer resource for which the API call is being made.
            var buyerName = "INSERT_BUYER_RESOURCE_NAME_HERE";

            // Retrieve credential parameters from the key JSON file.
            var credentialParameters = NewtonsoftJsonSerializer.Instance
                                       .Deserialize <JsonCredentialParameters>(
                System.IO.File.ReadAllText(ServiceKeyFilePath));

            // Create the credentials.
            var credentialInitializer = new ServiceAccountCredential.Initializer(
                credentialParameters.ClientEmail)
            {
                Scopes = new[] { RealTimeBiddingService.Scope.RealtimeBidding }
            }.FromPrivateKey(credentialParameters.PrivateKey);

            var oAuth2Credentials = new ServiceAccountCredential(credentialInitializer);

            // Use the credentials to create a client for the API service.
            var serviceInitializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = oAuth2Credentials,
                ApplicationName       = "FirstAPICall"
            };

            var realtimebidding = new RealTimeBiddingService(serviceInitializer);

            // Call the buyers.creatives.list method to list creatives for the given buyer.
            BuyersResource.CreativesResource.ListRequest request =
                realtimebidding.Buyers.Creatives.List(buyerName);
            request.View = BuyersResource.CreativesResource.ListRequest.ViewEnum.FULL;

            IList <Creative> creatives = request.Execute().Creatives;

            foreach (Creative creative in creatives)
            {
                Console.WriteLine("* Creative name: {0}", creative.Name);
            }

            Console.ReadLine();
        }
Ejemplo n.º 30
0
        public async Task ValidLocallySignedAccessToken_FromPrivateKey()
        {
            const string dummyServiceAccountCredentialFileContents = @"{
""private_key_id"": ""PRIVATE_KEY_ID"",
""private_key"": ""-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJJM6HT4s6btOsfe
2x4zrzrwSUtmtR37XTTi0sPARTDF8uzmXy8UnE5RcVJzEH5T2Ssz/ylX4Sl/CI4L
no1l8j9GiHJb49LSRjWe4Yx936q0Xj9H0R1HTxvjUPqwAsTwy2fKBTog+q1frqc9
o8s2r6LYivUGDVbhuUzCaMJsf+x3AgMBAAECgYEAi0FTXsu/zRswAUGaViQiHjrL
uU65BSHXNVjV/2fLNEKnGWGqpli68z1IXY+S2nwbUak7rnGsq9/0F6jtsW+hZbLk
KXUOuuExpeC5Kd6ngWX/f2jqmhlUabiQijU9cVk7pMq8EHkRtvlosnMTUAEzempu
QUPwn1PZHhmJkBvZ4lECQQDCErrxl+e3BwUDcS0yVEEmCNSG6xdXs2878b8rzbe7
3Mmi6SuuOLi3PU92J+j+f/MOdtYrk13mEDdYmd5dhrt5AkEAwPvDEsDT/W4y4h5n
gv1awGBA5aLFE1JNWM/Gwn4D1cGpEDHKFREaBtxMDCASpHJuw8r7zUywpKhmBZcf
GS37bwJANdSAKfbafLfjuhqwUJ9yGpykZm/a36aTmerp/bpn1iHdg+RtCzwMcDb/
TWSwibbvsflgWmHbz657y4WSWhq+8QJAWrpCNN/ZCk2zuGDo80lfUBAwkoVat8G6
wWU1oZyS+vzIGef+hLb8kHsjeZPej9eIwZ39kcBbT54oELrCkRjwGwJAQ8V2A7lT
ZUp8AsbVqF6rbLiiUfJMo2btGclQu4DEVyS+ymFA65tXDLUuR9EDqJYdqHNZJ5B8
4Z5p2prkjWTLcA==
-----END PRIVATE KEY-----"",
""client_email"": ""CLIENT_EMAIL"",
""client_id"": ""CLIENT_ID"",
""type"": ""service_account""}";

            var credentialParameters = NewtonsoftJsonSerializer.Instance.Deserialize <JsonCredentialParameters>(dummyServiceAccountCredentialFileContents);
            var initializer          = new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
            {
                Clock = new MockClock {
                    UtcNow = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                }
            };
            var cred = new ServiceAccountCredential(initializer.FromPrivateKey(credentialParameters.PrivateKey));

            Assert.False(cred.Scopes?.Any()); // HasScopes must be false for the type of access token we want to test.

            string accessToken = await cred.GetAccessTokenForRequestAsync("http://authurl/");

            string expectedToken =
                "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJDTElFTlRfRU1BSUwiLCJz" +
                "dWIiOiJDTElFTlRfRU1BSUwiLCJhdWQiOiJodHRwOi8vYXV0aHVybC8iLCJleHAiOjE0N" +
                "TE2MTAwMDAsImlhdCI6MTQ1MTYwNjQwMH0.WLljSaAqxMVZnAxFA2SvpA3n2WRlQW71Nb" +
                "CUkbN-ZI-EWoL-HhgiV_3ISrXMvbDHYhBR0vvtXE0PcRcsMEf51Y0jV4DXZ8hf-QJFq7O" +
                "Hrepwe93dnDE6uNVnbj41_0phuy1WKwae29Qp2aPI2Y8E8Z2tXQlF87E_MdgjXVeTF8k";

            Assert.Equal(expectedToken, accessToken);
        }