/// <summary> /// Authenticating to Google using a Service account /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount /// </summary> /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param> /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param> /// <returns>AnalyticsService used to make requests against the Analytics API</returns> public static TagmanagerService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes) { try { if (string.IsNullOrEmpty(serviceAccountCredentialFilePath)) { throw new Exception("Path to the service account credentials file is required."); } if (!File.Exists(serviceAccountCredentialFilePath)) { throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath); } if (string.IsNullOrEmpty(serviceAccountEmail)) { throw new Exception("ServiceAccountEmail is required."); } // For Json file if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json") { GoogleCredential credential; using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read)) { credential = GoogleCredential.FromStream(stream) .CreateScoped(scopes); } // Create the Analytics service. return(new TagmanagerService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Tagmanager Service account Authentication Sample", })); } else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12") { // If its a P12 file var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); // Create the Tagmanager service. return(new TagmanagerService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Tagmanager Authentication Sample", })); } else { throw new Exception("Unsupported Service accounts credentials."); } } catch (Exception ex) { throw new Exception("CreateServiceAccountTagmanagerFailed", ex); } }
public GoogleSheetsApi(string appName, ServiceAccountCredential serviceAccountCredential) { _sheetsService = new SheetsService(new BaseClientService.Initializer { ApplicationName = appName, HttpClientInitializer = serviceAccountCredential }); }
public void SetService(ServiceAccountCredential cred) { service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Calendar API Sample", }); }
public GoogleDriveApi(string appName, ServiceAccountCredential serviceAccountCredential) { _driveService = new DriveService(new BaseClientService.Initializer { ApplicationName = appName, HttpClientInitializer = serviceAccountCredential }); }
public ServiceAccountSigner(ServiceAccountCredential credential) { if (credential == null) { throw new ArgumentNullException("Credential must not be null."); } _credential = credential; }
/// <summary> /// Gets the access token in service account flow. /// </summary> /// <returns>The token response.</returns> protected virtual TokenResponse GetAccessTokenForServiceAccount() { ServiceAccountCredential credential = this.GetServiceAccountCredential(); Task <string> task = credential.GetAccessTokenForRequestAsync(); task.Wait(); return(credential.Token); }
private DatastoreService GetDatastoreService(ServiceAccountCredential credential, Dictionary <string, string> assets) { return(new DatastoreService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = assets[Constants.ASSET_NAME_APPNAME], })); }
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 }
private void btntaikhoahoc_Click(object sender, EventArgs e) { gridView1.OptionsBehavior.Editable = false; string[] scopes = new string[] { DriveService.Scope.Drive, // Full access DriveService.Scope.DriveAppdata, DriveService.Scope.DriveFile, DriveService.Scope.DriveMetadata, DriveService.Scope.DriveScripts, //DriveService.Scope.DriveReadonly, DriveService.Scope.DrivePhotosReadonly, }; //string ACTIVITY_ID = "z12gtjhq3qn2xxl2o224exwiqruvtda0i"; Console.WriteLine("Plus API - Service Account"); Console.WriteLine("=========================="); String serviceAccountEmail = "*****@*****.**";// "SERVICE_ACCOUNT_EMAIL_HERE"; var certificate = new X509Certificate2(@"moodlehv-teacher-1594910513742-b991fcd2279e.p12", "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes //new[] { PlusService.Scope.PlusMe } }.FromCertificate(certificate)); DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "e-learningHVStudentDesktopApp", }); string test = ds.Rows[0]["Check"].ToString(); for (int i = 0; i < ds.Rows.Count; i++) { if (ds.Rows[i]["Check"].ToString() != "") { string strPercent = ds.Rows[i]["status"].ToString(); string strStatusDU = ds.Rows[i]["statusDU"].ToString(); if ((bool.Parse(ds.Rows[i]["Check"].ToString()) == true) && (strPercent == "100%") && (strStatusDU == "Finished")) { continue; } if (bool.Parse(ds.Rows[i]["Check"].ToString()) == true) { // ID File lấy tài khoản Google Drive của bạn string fileId = ds.Rows[i]["Id"].ToString();// "1RtPMXrk3WJ9QYwcM4ogBojgB-nOz63rn"; string PathToSave = ds.Rows[i]["CourseName"].ToString(); long fileSize = long.Parse(ds.Rows[i]["size"].ToString()); if ((strPercent != "") && (strPercent != "0%")) { continue; } Task.Run(() => { Download(service, fileId.ToString(), PathToSave, fileSize, this); }); } } } }
public void DoNothing() { var serviceAccountEmail = "***.apps.googleusercontent.com"; var certificate = new X509Certificate2( @"***-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable); //var t = Google.Apis.Auth.OAuth2.ServiceAccountCredential var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { Google.Apis.Datastore.v1beta3.DatastoreService.Scope.Datastore.ToString().ToLower() } }.FromCertificate(certificate)); // Create the service. var service = new DatastoreService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "***", }); var request = new Google.Apis.Datastore.v1beta3.Data .BeginTransactionRequest(); // GoogleData.BlindWriteRequest(); var entity = new Entity(); entity.Key = new Google.Apis.Datastore.v1beta3.Data.Key(); entity.Key.Path = new List <Google.Apis.Datastore.v1beta3.Data.PathElement>(); entity.Key.Path.Add(new Google.Apis.Datastore.v1beta3.Data.PathElement() { Kind = "KindTest", Name = "name" }); var firstName = new Google.Apis.Datastore.v1beta3.Data.PropertyReference();//.Property(); //firstName. //firstName.Values = new List<Google.Apis.Datastore.v1beta3.Data.Value>(); //firstName. .Values.Add(new Google.Apis.Datastore.v1beta3.Data.Value { StringValue = "FName" }); entity.Properties = new Dictionary <string, Google.Apis.Datastore.v1beta3.Data.Value>(); entity.Properties["firstName"] = new Google.Apis.Datastore.v1beta3.Data.Value { StringValue = "FName" }; entity.Properties.Add("FirstName", new Google.Apis.Datastore.v1beta3.Data.Value { StringValue = "FName" }); //request.Mutation = new Mutation(); //request.Mutation.Upsert = new List<Entity>(); //request.Mutation.Upsert.Add(entity); //var response = service.Datasets.BlindWrite(request, "***").Execute(); }
public GaData RunGAAPI(DateTime start, DateTime end, bool iscampaign = false, string campaign = "", string source = "", string medium = "") { //var _logger = EngineContext.Current.Resolve<ILogger>(); string[] scopes = new string[] { AnalyticsService.Scope.Analytics, // view and manage your Google Analytics data AnalyticsService.Scope.AnalyticsManageUsersReadonly }; // View Google Analytics data //string keyFilePath = System.IO.Path.Combine(System.Web.HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data"), "Get Andorra Analytics Values-73dc38419daa.p12"); string path = ConfigurationManager.AppSettings["p12key"]; string keyFilePath; if (path == "localhost") { keyFilePath = System.IO.Path.Combine(System.Web.HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data"), "Get Andorra Analytics Values-73dc38419daa.p12"); } else { keyFilePath = System.IO.Path.Combine(path, "Get Andorra Analytics Values-73dc38419daa.p12"); } //string keyFilePath = Path.Combine(_webHelper.GetApp_DataPath(), EngineContext.Current.Resolve<FC_Settings_GoogleAPI>().GA_ApiFilename); string serviceAccountEmail = "*****@*****.**"; // found in developer console //loading the Key file var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Get Andorra Analytics Values"// EngineContext.Current.Resolve<Nop.Core.Domain.FC.Settings.FC_Settings_GoogleAPI>().GA_ApiKey }); DataResource.GaResource.GetRequest result = service.Data.Ga.Get("ga:70910396", start.ToString("yyyy-MM-dd"), end.ToString("yyyy-MM-dd"), "ga:sessions,ga:users,ga:newUsers,ga:bounces,ga:avgSessionDuration,ga:pageviews"); //result.Dimensions = "ga:date,ga:countryIsoCode,ga:deviceCategory,ga:source,ga:medium,ga:campaign"; result.Sort = "ga:date"; result.Dimensions = "ga:date"; if (iscampaign) { result.Filters = "ga:campaign!=(not set)"; } if (campaign != "" && source != "" && medium != "") { result.Filters = "ga:campaign==" + campaign + ";ga:source==" + source + ";ga:medium==" + medium; } //result.Filters = "ga:campaign==" + utm_name + ";ga:source==" + utm_source + ";ga:medium==" + utm_medium; result.MaxResults = 10000; //_logger.Information("FC_GA EXECUTE" + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), null, null); return(result.Execute()); }
/// <summary> /// Scoped cannot be used, but full access is specified. /// UNTESTED /// </summary> /// <param name="privateKey"></param> /// <param name="serviceAccountEmail"></param> public BigtableCredentials(string privateKey, string serviceAccountEmail) { // Load certificate and assemble credentials by hand _serviceCredentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = BigtableConstants.Scopes.All }.FromPrivateKey(privateKey)); }
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); } }
public GcpObjectStorage(IObjectStorageConfiguration configuration) { var credential = GoogleCredential.FromJson(configuration.Credential); var saCredential = (ServiceAccountCredential)credential.UnderlyingCredential; _saCredential = saCredential; _storageClient = StorageClient.Create(credential); _configuration = configuration; }
public AuthorizationDelegatingHandler(ServiceAccountCredential accountCredential, string emailAddress, string scopes) { _accountCredential = accountCredential; _emailAddress = emailAddress; _scopes = scopes; _client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); }
/// <summary> /// Loads calendar events /// </summary> /// <returns>Awaitable task of Events in list form</returns> public List <Cal.Event> GetData() { string serviceAccount = "*****@*****.**"; string fileName = System.Web.HttpContext.Current.Server.MapPath("..\\") + "MagicMirror.p12"; var certificate = new X509Certificate2(fileName, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccount) { Scopes = new[] { CalendarService.Scope.CalendarReadonly }, User = serviceAccount }.FromCertificate(certificate)); var calendarService = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "MagicMirror" }); var calendarListResource = calendarService.CalendarList.List().Execute(); //await calendarService.CalendarList.List().ExecuteAsync(); //calendarService.CalendarList.List().Execute().Items; var myCalendar = calendarListResource.Items[0]; string pageToken = null; Events = new List <Cal.Event>(); //do //{ //TODO: Make configuration items var activeCalendarList = calendarService.Events.List(calendarOwner); activeCalendarList.PageToken = pageToken; activeCalendarList.MaxResults = 3; activeCalendarList.TimeMax = DateTime.Now.AddMonths(3); activeCalendarList.TimeMin = DateTime.Now; activeCalendarList.SingleEvents = true; activeCalendarList.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; var calEvents = activeCalendarList.Execute(); var items = calEvents.Items; foreach (var item in items) { Events.Add(new Cal.Event() { Summary = item.Summary, StartTimeStr = (item.Start.DateTime.HasValue ? item.Start.DateTime.Value : DateTime.Parse(item.Start.Date)).ToString(), EndTimeStr = (item.End.DateTime.HasValue ? item.End.DateTime.Value : DateTime.Parse(item.End.Date)).ToString() }); } return(Events); }
public GoogleCloudPrintService(string serviceAccountEmail, string keyFilePath, string keyFileSecret, string source) { _serviceAccountEmail = serviceAccountEmail; _keyFilePath = keyFilePath; _keyFileSecret = keyFileSecret; _source = source; _credentials = Authorize(); }
private async void EnviarCorreoRecuperacion(Usuario usuario) { // string nombreAplicacion = _configuration.GetValue<string>("Correo:NombreAplicacion"); string muroAgilEmail = _configuration.GetValue <string>("Correo:Direccion"); string muroAgilEmailAlias = _configuration.GetValue <string>("Correo:DireccionAlias"); string muroAgilNombre = _configuration.GetValue <string>("Correo:Nombre"); string servAccountEmail = _configuration.GetValue <string>("Correo:ServiceAccount:client_email"); string servAccountPrivKey = _configuration.GetValue <string>("Correo:ServiceAccount:private_key"); string muroAgilDominio = _configuration.GetValue <string>("Correo:Dominio"); if (string.IsNullOrEmpty(muroAgilDominio)) { muroAgilDominio = Request.Host.Value; } ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(servAccountEmail) { User = muroAgilEmail, Scopes = new[] { GmailService.Scope.GmailSend } }.FromPrivateKey(servAccountPrivKey) ); bool gotAccessToken = await credential.RequestAccessTokenAsync(CancellationToken.None); if (gotAccessToken) { GmailService service = new GmailService( new BaseClientService.Initializer() { // ApplicationName = nombreAplicacion, HttpClientInitializer = credential } ); MailAddress fromAddress = new MailAddress(muroAgilEmailAlias, muroAgilNombre, System.Text.Encoding.UTF8); MailAddress toAddress = new MailAddress(usuario.Correo, usuario.Nombre, System.Text.Encoding.UTF8); MailMessage message = new MailMessage(fromAddress, toAddress) { Subject = "Recuperación de Contraseña - Muro Ágil", Body = CuerpoCorreo.getCuerpoRecuperacion(usuario.Correo, usuario.Nombre, usuario.TokenRecupContr, muroAgilDominio), SubjectEncoding = Encoding.UTF8, HeadersEncoding = Encoding.UTF8, BodyEncoding = Encoding.UTF8, IsBodyHtml = true }; MimeMessage mimeMessage = MimeMessage.CreateFromMailMessage(message); MemoryStream stream = new MemoryStream(); mimeMessage.WriteTo(stream); string rawMessage = Base64UrlEncode(stream.ToArray()); service.Users.Messages.Send(new Message { Raw = rawMessage }, muroAgilEmail).Execute(); } }
public virtual void ProcessRequest(HttpContext context) { try { HttpRequest request = context.Request; // get settings WobCredentials credentials = new WobCredentials( WebConfigurationManager.AppSettings["ServiceAccountId"], WebConfigurationManager.AppSettings["ServiceAccountPrivateKey"], WebConfigurationManager.AppSettings["ApplicationName"], WebConfigurationManager.AppSettings["IssuerId"]); string loyaltyClassId = WebConfigurationManager.AppSettings["LoyaltyClassId"]; string offerClassId = WebConfigurationManager.AppSettings["OfferClassId"]; // OAuth - setup certificate based on private key file X509Certificate2 certificate = new X509Certificate2( AppDomain.CurrentDomain.BaseDirectory + credentials.serviceAccountPrivateKey, "notasecret", X509KeyStorageFlags.Exportable); // create service account credential ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(credentials.serviceAccountId) { Scopes = new[] { "https://www.googleapis.com/auth/wallet_object.issuer" } }.FromCertificate(certificate)); // create the service var woService = new WalletobjectsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Wallet Objects API Sample", }); // get the class type string type = request.Params["type"]; // insert the class if (type.Equals("loyalty")) { LoyaltyClass loyaltyClass = Loyalty.generateLoyaltyClass(credentials.IssuerId, loyaltyClassId); woService.Loyaltyclass.Insert(loyaltyClass).Execute(); } else if (type.Equals("offer")) { OfferClass offerClass = Offer.generateOfferClass(credentials.IssuerId, offerClassId); woService.Offerclass.Insert(offerClass).Execute(); } } catch (Exception e) { Console.Write(e.StackTrace); } }
public override async Task Execute(MessageData data) { var args = data.GetAs <Arguments>(); string serviceAccountEmail = "*****@*****.**"; var certificate = new X509Certificate2(@"keyfile.p12", "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { "https://www.googleapis.com/auth/androidpublisher" } }.FromCertificate(certificate)); var service = new AndroidPublisherService( new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "GooglePlay API Sample", }); // try catch this function because if you input wrong params ( wrong token) google will return error. //var request = service.Inappproducts.List("de.flou.hypixel.skyblock"); var request = service.Purchases.Products.Get( args.PackageName, args.ProductId, args.Token); try { Console.WriteLine($"Purchasing Product with id: {args.ProductId}"); var purchaseState = await request.ExecuteAsync(); //get purchase'status Console.WriteLine(JsonConvert.SerializeObject(purchaseState)); if (((long)purchaseState.PurchaseTimeMillis / 1000).ThisIsNowATimeStamp() < DateTime.Now - TimeSpan.FromDays(7)) { throw new CoflnetException("purchase_expired", "This purchase is older than a week and thus expired"); } var days = int.Parse(args.ProductId.Split('_')[1]); UserService.Instance.SavePurchase(data.User, days, purchaseState.OrderId); } catch (Exception e) { Logger.Instance.Error("Purchase failure " + e.Message); throw new CoflnetException("purchase_failed", "Purchase failed, please contact the admin"); } await data.SendBack(data.Create("accepted", "payment was accepted enjoy your premium", A_WEEK)); }
private ServiceAccountCredential GetCredentials() { var credentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(ServiceAccountEmail) { Scopes = new[] { CalendarService.Scope.Calendar } }.FromCertificate(this.serviceCertificate)); return(credentials); }
public API(string serviceAccountEmail, string keyPath, string[] scopes, string impersonationUserEmail = null, string directoryServices_Domain = null) { this.ServiceAccountEmail = serviceAccountEmail; this.KeyPath = keyPath; this.Scopes = scopes; this.ImpersonationUserEmail = impersonationUserEmail; this.DirectoryServices_Domain = directoryServices_Domain; this.Credentials = GetServiceAccountCredentials(); }
/// <summary> /// Access to all Gmail services. /// </summary> /// <param name="accountCredential">The Google Account Credentials</param> /// <param name="emailAddress">The emailaddress of the user to impersonate</param> /// <param name="scopes">The required Gmail scopes, separated by space</param> public GmailClient(ServiceAccountCredential accountCredential, string emailAddress, string scopes) { _proxy = new GmailProxy(new AuthorizationDelegatingHandler(accountCredential, emailAddress, scopes)); Messages = new MessageService(_proxy); Drafts = new DraftService(_proxy); Labels = new LabelService(_proxy); Threads = new ThreadService(_proxy); History = new HistoryService(_proxy); }
/// <summary> /// Gets the DirectoryService from the given credentials and application name. /// </summary> /// <param name="credentials">ServiceAccountCredentials to use for the service</param> /// <param name="appName">Application name to use for the service</param> /// <returns></returns> private static DirectoryService GetDirectoryService(ServiceAccountCredential credentials, string appName = "Test Application") { var service = new DirectoryService(new BaseClientService.Initializer() { ApplicationName = appName, HttpClientInitializer = credentials }); return(service); }
/// <summary> /// Gets the ServiceAccountCredential from the given service account, account to impersonate, scopes, and the certificate /// </summary> /// <param name="serviceAccount">Service account name</param> /// <param name="impersonatedAccount">Account that the service account will impersonate</param> /// <param name="scopes">Scopes to specify for the credentials</param> /// <param name="certificate">PKCS12 private key</param> /// <returns></returns> private static ServiceAccountCredential GetServiceAccountCredentials(string serviceAccount, string impersonatedAccount, string[] scopes, X509Certificate2 certificate) { var creds = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccount) { User = impersonatedAccount, Scopes = scopes }.FromCertificate(certificate)); return(creds); }
private ServiceAccountCredential GetCredentials() { var initializer = new ServiceAccountCredential.Initializer(configuration.GoogleClientEmail); initializer.Scopes = Scopes; var result = new ServiceAccountCredential(initializer.FromPrivateKey(configuration.GoogleClientPrivateKey)); return(result); }
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); } }
string keyFile = @"D:\key.p12"; //file link to downloaded key with p12 extension protected void Page_Load(object sender, EventArgs e) { string Token = Convert.ToString(GetAccessToken(ServiceAccountUser, keyFile, SCOPE_ANALYTICS_READONLY)); accessToken.Value = Token; var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable); var credentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(ServiceAccountUser) { Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly } }.FromCertificate(certificate)); var service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credentials, ApplicationName = "Google Analytics API" }); string profileId = "ga:53861036"; string startDate = "2016-04-01"; string endDate = "2016-04-30"; string metrics = "ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:visits"; DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics); GaData data = request.Execute(); List <string> ColumnName = new List <string>(); foreach (var h in data.ColumnHeaders) { ColumnName.Add(h.Name); } List <double> values = new List <double>(); foreach (var row in data.Rows) { foreach (var item in row) { values.Add(Convert.ToDouble(item)); } } values[3] = Math.Truncate(100 * values[3]) / 100; txtSession.Text = values[0].ToString(); txtUsers.Text = values[1].ToString(); txtPageViews.Text = values[2].ToString(); txtBounceRate.Text = values[3].ToString(); txtVisits.Text = values[4].ToString(); }
/// <summary> /// Retrieves Videos Feeds from YouTube using OAuth 2.0. /// </summary> /// <returns></returns> public List <SearchResult> RetriveVideosUsingOAuth(string searchTerm) { String serviceAccountEmail = OAUTH_SERVICE_ACCOUNT_EMAIL; var certificate = new X509Certificate2(OAUTH_LOCAL_KEY_FILE, OAUTH_PASSWORD, X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { YouTubeService.Scope.YoutubeReadonly } }.FromCertificate(certificate)); // Create the service. var service = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "YouTube API Sample", }); SearchResource.ListRequest listRequest = service.Search.List("snippet"); listRequest.Fields = "items(id,snippet(title, description, publishedAt, thumbnails, channelId, channelTitle))"; listRequest.Type = ResourceTypes.Video; listRequest.MaxResults = MAX_RESULTS_PER_PAGE; if (!string.IsNullOrEmpty(PUBLISHED_FROM_DATE)) { listRequest.PublishedAfter = DateTime.ParseExact(PUBLISHED_FROM_DATE, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture); } if (string.IsNullOrEmpty(LOCATION)) { listRequest.Location = LOCATION; } if (string.IsNullOrEmpty(LOCATION_RADIUS)) { listRequest.LocationRadius = LOCATION_RADIUS; } listRequest.Q = searchTerm; listRequest.Order = SearchResource.ListRequest.OrderEnum.Date; SearchListResponse searchResponse = listRequest.Execute(); List <SearchResult> results = new List <SearchResult>(); results.AddRange(searchResponse.Items); string nextPageToken = searchResponse.NextPageToken; while (searchResponse.Items.Count == MAX_RESULTS_PER_PAGE) { listRequest.PageToken = nextPageToken; searchResponse = listRequest.Execute(); results.AddRange(searchResponse.Items); nextPageToken = searchResponse.NextPageToken; } return(results); }
private static void RunExportOptions(ExportOptions options) { if (!file.Exists(keyFilePath)) { throw new InvalidOperationException("No 'service-account-private-key.p12' in the current working directory"); } // Load the Key file var certificate = new X509Certificate2( keyFilePath, "notasecret", X509KeyStorageFlags.Exportable ); // If modifying these scopes, delete your previously saved credentials var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(options.ServiceAccountEmail) { Scopes = new[] { DriveService.Scope.Drive, SheetsService.Scope.Spreadsheets }, }.FromCertificate(certificate) ); // Create Google driver service. driverService = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = options.ApplicationName }); // Create Google Sheets API service. sheetService = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = options.ApplicationName, }); var spreadsheetId = GetSpreadsheetId(options); if (string.IsNullOrEmpty(spreadsheetId)) { // Create sheet if does not exist spreadsheetId = CreateSpreadsheet(options); InitialCellValues(spreadsheetId, options); Console.WriteLine($"Sheet name '{spreadsheetId}' is created"); } foreach (var sheetName in options.SupportedLanguages) { ExportToJson(spreadsheetId, sheetName, options); } }