private static GoogleMailSettingsService CreateGoogleMailService() { // Get your service account email from Google Developer's Console // Read more: https://developers.google.com/identity/protocols/OAuth2ServiceAccount const string SERVICE_ACCT_EMAIL = "<YOUR SERVICE KEY>@developer.gserviceaccount.com"; //Generate your .p12 key in the Google Developer Console and associate it with your project. var certificate = new X509Certificate2("Key.p12", "notasecret", X509KeyStorageFlags.Exportable); var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(SERVICE_ACCT_EMAIL) { User = "******", // A user with administrator access. Scopes = new[] { "https://apps-apis.google.com/a/feeds/emailsettings/2.0/" } }.FromCertificate(certificate); var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer); if (!credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result) throw new InvalidOperationException("Access token failed."); var requestFactory = new GDataRequestFactory(null); requestFactory.CustomHeaders.Add("Authorization: Bearer " + credential.Token.AccessToken); // Replace the name of your domain and the Google Developer project you created... GoogleMailSettingsService service = new GoogleMailSettingsService("vuwall.com", "signatures"); service.RequestFactory = requestFactory; return service; }
/// <summary> /// Constructor for the Google Analytics Helper /// </summary> /// <param name="serviceAccountEmail">Service account email for the Google API. Looks like [email protected]</param> /// <param name="applicationName">The name of the Google API Application</param> /// <param name="p12CertificatePath">Path to the downloaded p12 certificate</param> /// <param name="certificatePassword">Password to the p12 certificate - default "notasecret" </param> public Helper(string serviceAccountEmail, string applicationName, string p12CertificatePath, string certificatePassword) { var certificate = new X509Certificate2(p12CertificatePath, certificatePassword, X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { AnalyticsService.Scope.Analytics } }.FromCertificate(certificate)); service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName, }); }
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.That(cred.Scopes?.Any(), Is.False); // 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.That(accessToken, Is.EqualTo(expectedToken)); }
public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath, string applicationName) { if (!File.Exists(keyFilePath)) { throw new FileNotFoundException("Given key file is not found", keyFilePath); } // Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents DriveService.Scope.DriveAppdata, // view and manage its own configuration data DriveService.Scope.DriveAppsReadonly, // view your drive apps DriveService.Scope.DriveFile, // view and manage files created by this app DriveService.Scope.DriveMetadataReadonly, // view metadata for files DriveService.Scope.DriveReadonly, // view files and documents on your drive DriveService.Scope.DriveScripts }; // modify your app scripts var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); // Create the service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName, }); return service; }
/// <summary> /// Create a service connection to google. /// </summary> /// <param name="userEmail">The API email to use for authentication.</param> /// <param name="gService">The type of service to connect to.</param> /// <returns>Returns an open connection to the google api service, or null.</returns> private static BaseClientService BuildService(string userEmail, GoogleServices gService = GoogleServices.Directory) { X509Certificate2 certificate = new X509Certificate2(Properties.Resources.gsd_api,"notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL) { Scopes = Scopes, User = userEmail }.FromCertificate(certificate)); switch (gService) { case GoogleServices.Directory: DirectoryService directoryService = new DirectoryService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "GSD GAMS", }); return directoryService; case GoogleServices.Drive: DriveService driveService = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "GSD GAMS", }); return driveService; } return null; }
/// <summary> /// Initialise la connexion avec Google Calendar /// </summary> /// <param name="privateKey"></param> /// <param name="googleAccount"></param> /// <returns></returns> public bool InitCnx() { Log.Debug("Initialisation de la connexion avec Google ..."); // Si la fonction n'est pas activée, on passe tout de suite if (!p_isActivated) { return false; } try { string[] scopes = new string[] { CalendarService.Scope.Calendar, // Manage your calendars CalendarService.Scope.CalendarReadonly // View your Calendars }; var certificate = new X509Certificate2(p_privateKey, "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(p_googleAccount) { Scopes = scopes }.FromCertificate(certificate)); // Create Google Calendar API service. p_myService = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "PlanningLAB", }); } catch (Exception err) { Log.Error("Erreur Authentification Google {" + p_googleAccount + "} - {" + p_privateKey + "} :", err); return false; } return true; }/// <summary>
public static AnalyticsService authentify(string keyFilePath, string serviceAccountEmail) { string[] scopes = new string[] { AnalyticsService.Scope.Analytics, // view and manage your Google Analytics data AnalyticsService.Scope.AnalyticsManageUsers}; // View Google Analytics data if (!File.Exists(keyFilePath)) { MessageBox.Show("An Error occurred - Key file does not exist \n" + keyFilePath, "KeyFile not found", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } //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 = "Analytics Add-In", }); return service; }
public ShoppingContentService GetShoppingContentService() { if (_contentService == null) { string appPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; var key = string.Format(@"{0}{1}{2}", appPath, Path.DirectorySeparatorChar, keyPath); var certificate = new X509Certificate2(key, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { ShoppingContentService.Scope.Content } }.FromCertificate(certificate)); // Create the service. _contentService = new ShoppingContentService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "VirtoCommerce shopping integration" }); } return _contentService; }
public async static Task<int> GetPvAsync() { // Azure Web サイトで動かす場合には WEBSITE_LOAD_USER_PROFILE = 1 必須 var file = ConfigurationManager.AppSettings["analyticsKeyFile"]; var analyticsKeyFile = file[0] == '~' ? HttpContext.Current.Server.MapPath(file) : file; var certificate = new X509Certificate2(analyticsKeyFile, "notasecret", X509KeyStorageFlags.Exportable); // Scopes は指定しないとエラーになる var analyticsCredentialId = ConfigurationManager.AppSettings["analyticsCredentialId"]; var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(analyticsCredentialId) { Scopes = new[] { AnalyticsService.Scope.Analytics, AnalyticsService.Scope.AnalyticsReadonly } }.FromCertificate(certificate)); // HttpClientInitializer に credential 入れるのは違和感あるけど正しいらしい var service = new AnalyticsService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "TweetPV", }); // Azure は UTC なので +9 時間して -1 日 var date = DateTime.UtcNow.AddHours(9).AddDays(-1).ToString("yyyy-MM-dd"); // ****** はメモしたビューの ID var analyticsViewId = ConfigurationManager.AppSettings["analyticsViewId"]; var data = await service.Data.Ga.Get("ga:" + analyticsViewId, date, date, "ga:pageviews").ExecuteAsync(); return int.Parse(data.Rows[0][0]); }
public MainWindow() { string[] scopes = new string[] { DriveService.Scope.Drive }; InitializeComponent(); var keyFilePath = @"c:\file.p12"; // Downloaded from https://console.developers.google.com var serviceAccountEmail = "*****@*****.**"; // found https://console.developers.google.com //loading the Key file var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Drive API Sample", }); FilesResource.ListRequest request = service.Files.List(); FileList files = request.Execute(); foreach (var file in files.Items) { Console.WriteLine(file.Title); } }
public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath) { if (!System.IO.File.Exists(keyFilePath)) { //Console.WriteLine("Key File does not exist"); return null; } string[] scopes = new string[] { DriveService.Scope.Drive }; var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); try { ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "PepitoTW" }); //Console.WriteLine("Authenticate Success"); return service; } catch (Exception ex) { //Console.WriteLine(ex.InnerException); return null; } }
public static void Main(string[] args) { Console.WriteLine("Plus API - Service Account"); Console.WriteLine("=========================="); String serviceAccountEmail = "SERVICE_ACCOUNT_EMAIL_HERE"; var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { PlusService.Scope.PlusMe } }.FromCertificate(certificate)); // Create the service. var service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Plus API Sample", }); Activity activity = service.Activities.Get(ACTIVITY_ID).Execute(); Console.WriteLine(" Activity: " + activity.Object__.Content); Console.WriteLine(" Video: " + activity.Object__.Attachments[0].Url); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
internal Initializer(ServiceAccountCredential other) : base(other) { Id = other.Id; ProjectId = other.ProjectId; User = other.User; Scopes = other.Scopes; Key = other.Key; }
internal Initializer(ServiceAccountCredential other) : base(other) { Id = other.Id; ProjectId = other.ProjectId; User = other.User; Key = other.Key; KeyId = other.KeyId; UseJwtAccessWithScopes = other.UseJwtAccessWithScopes; }
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 static DriveService Get() { string[] scopes = { DriveService.Scope.Drive, DriveService.Scope.DriveFile }; var credentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(GoogleDriveServiceAccountEmail) { Scopes = scopes }.FromPrivateKey(GoogleDrivePrivateKey)); return new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credentials }); }
/// <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; }
private static IConfigurableHttpClientInitializer Authenticate(String ownerToFilter) { X509Certificate2 cert = new X509Certificate2(ConfigurationManager.AppSettings["accountServiceP12"], "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); ServiceAccountCredential cred = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(ConfigurationManager.AppSettings["accountServiceName"]) { User = ownerToFilter, Scopes = new[] { DriveService.Scope.Drive }, }.FromCertificate(cert)); return cred; }
public void Connect() { string strCertFilePath = Assembly.GetExecutingAssembly().Location + @"..\..\" + m_strCertFileName; string[] scopes = {DriveService.Scope.Drive}; // Full access X509Certificate2 certAuth = new X509Certificate2(strCertFilePath, "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(m_strServiceAccountEmail) {Scopes = scopes}.FromCertificate (certAuth)); }
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.That(cred.Scopes?.Any(), Is.False); // 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.That(accessToken, Is.EqualTo(expectedToken)); }
/// <summary> /// Creates a Queryer object to perform queries on Google Analytics, using a Service Account /// </summary> /// <param name="keyFilePath">Path to the Service Account's key file (what you download when you create a service account)</param> /// <param name="keyPassword">The password for the key file (defaults to "notapassword" when you create the service account)</param> /// <param name="serviceAccountEmail">The email associated with the service account (in format "(number)@developer.gserviceaccount.com")</param> /// <param name="applicationName">Name of application (I used the Name field in the Project Summary panel in https://code.google.com/apis/console/ )</param> public Queryer(string keyFilePath, string keyPassword, string serviceAccountEmail, string applicationName) { var key = new X509Certificate2(keyFilePath, keyPassword, X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { AnalyticsService.Scope.Analytics } }.FromCertificate(key)); // Create the service. _service = new AnalyticsService(new BaseClientService.Initializer() { ApplicationName = applicationName, HttpClientInitializer = credential }); }
public DriveUtils(String keyEmail, String keyFilePath, String parentDirectoryId) { var certificate = new X509Certificate2(System.IO.File.ReadAllBytes(keyFilePath), "notasecret", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(keyEmail) { Scopes = new[] { DriveService.Scope.Drive } }.FromCertificate(certificate)); this.driveService = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "kawaldesa", }); this.parentDirectoryId = parentDirectoryId; }
/// <summary> /// Gets credentials you can use to authenticate with Google services. /// </summary> public static IConfigurableHttpClientInitializer GetCredentials( Initializer init) { if (AmIRunningOnGoogleComputeEngine()) { return new ComputeCredential(new ComputeCredential.Initializer()); } if (init.LogWriter != null && init.LogWriter.IsLoggingEnabled()) init.LogWriter.Write("Using credentials from " + init.ServiceAccountP12KeyPath + "."); var certificate = new X509Certificate2(init.ServiceAccountP12KeyPath, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(init.ServiceAccountEmail) { Scopes = init.scopes, }.FromCertificate(certificate)); return credential; }
public void Validate() { const string serviceAccountEmail = "*****@*****.**"; string serviceAccountCertPath = System.Web.HttpContext.Current.Server.MapPath("~/Assets/Gmail/lcps-admin-dir.p12"); const string serviceAccountCertPassword = "******"; const string userEmail = "*****@*****.**"; var certificate = new X509Certificate2(serviceAccountCertPath, serviceAccountCertPassword, X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes, User = userEmail }.FromCertificate(certificate)); var service = new DirectoryService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName }); UsersResource.ListRequest request = service.Users.List(); request.Customer = "my_customer"; request.OrderBy = UsersResource.ListRequest.OrderByEnum.Email; // List users. UsersResource.ListRequest.Execute().UsersValue IList<User> users = request.Execute().UsersValue; if (users != null && users.Count > 0) { foreach (var userItem in users) { string pe = userItem.PrimaryEmail; } } else { throw new Exception("No users"); } }
public AnalyticsHelper(string analyticsKeyFile) { // Azure Web サイトで動かす場合には WEBSITE_LOAD_USER_PROFILE = 1 必須 var certificate = new X509Certificate2(analyticsKeyFile, "notasecret", X509KeyStorageFlags.Exportable); // Scopes は指定しないとエラーになる var analyticsCredentialId = ConfigurationManager.AppSettings["analyticsCredentialId"]; var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(analyticsCredentialId) { Scopes = new[] { AnalyticsService.Scope.Analytics, AnalyticsService.Scope.AnalyticsReadonly } }.FromCertificate(certificate)); // HttpClientInitializer に credential 入れるのは違和感あるけど正しいらしい _service = new AnalyticsService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "TweetPVSample", }); }
public StorageFixture() { Config = new ConfigurationBuilder() .SetBasePath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..")) .AddEnvironmentVariables() .AddUserSecrets() .Build(); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(Config["GoogleEmail"]) { Scopes = new[] {StorageService.Scope.DevstorageFullControl} }.FromCertificate(new X509Certificate2(Convert.FromBase64String(Config["GoogleP12PrivateKey"]), "notasecret", X509KeyStorageFlags.Exportable))); _client = new StorageService(new BaseClientService.Initializer { HttpClientInitializer = credential }); }
public GoogleApiHelper( string p12Path, string serviceAccountEmail, string applicationName, string calendarId, DateTime startCalendarQuery, DateTime endCalendarQuery) { try { var certificate = new X509Certificate2(p12Path, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { CalendarService.Scope.Calendar } }.FromCertificate (certificate)); var initializer = new BaseClientService.Initializer(); initializer.HttpClientInitializer = credential; initializer.ApplicationName = applicationName; var service = new CalendarService(initializer); var queryStart = startCalendarQuery; var queryEnd = endCalendarQuery; var query = service.Events.List(calendarId); query.TimeMin = queryStart; query.TimeMax = queryEnd; var events = query.Execute().Items; _mEventList = events.Select(e => new GoogleCalendarEvent(DateTime.Parse(e.Start.Date), e.Summary)).ToList(); _mEventList.Sort((e1, e2) => e1.Date.CompareTo(e2.Date)); } catch (Exception e) { throw new Exception(string.Format("Exception in GoogleAPIHelper constructor: {0}", e.Message)); } }
public string GetOAuth2AccessToken(string emailAddress) { var certificate = new X509Certificate2(_certificatePath.Value, _gmailSettings.ServiceAccountCertPassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(_gmailSettings.ServiceAccountEmailAddress) { Scopes = new[] { GoogleScope.ImapAndSmtp.Name }, User = emailAddress }.FromCertificate(certificate)); var success = credential.RequestAccessTokenAsync(CancellationToken.None).Result; return success ? credential.Token.AccessToken : string.Empty; }
public GoogleCalendarService(string serviceAccountEmail, string serviceAcountCertFilePath) { // We need to add the X509KeyStorageFlags.MachineKey to work in shared hosting were we // don't have access to the user account // http://stackoverflow.com/questions/1345262/an-internal-error-occurred-when-loading-pfx-file-with-x509certificate2 // On Arvixe the site would lockup and kill the AppPool X509Certificate2 certificate = new X509Certificate2(HostingEnvironment.MapPath(serviceAcountCertFilePath), "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { CalendarService.Scope.Calendar } }.FromCertificate(certificate)); Service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "www.providence-pca.net", }); }
// GET: Google/GoogleConnect public ActionResult Index() { string p = HttpContext.Server.MapPath("~/Assets/API-Project.p12"); String serviceAccountEmail = "*****@*****.**"; X509Certificate2 certificate = new X509Certificate2(p, "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser }, User = "******" }.FromCertificate(certificate)); var service = new DirectoryService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "LCPS-MSE-01", }); //service.Users.List().Domain = "k12lcps.org"; var list = service.Users.List(); var results = list.Execute(); foreach (User u in results.UsersValue) { string n = u.Name.FullName; int x = 0; x++; } return View(); }
// BigQuery public static BigqueryService GetService() { var certificateFileName = ConfigurationManager.AppSettings["certificateFileName"]; var certificatePassword = ConfigurationManager.AppSettings["certificatePassword"]; var serviceAccountEmail = ConfigurationManager.AppSettings["serviceAccountEmail"]; var applicationName = ConfigurationManager.AppSettings["applicationName"]; var path = Path.Combine(new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName, certificateFileName); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { BigqueryService.Scope.Bigquery, BigqueryService.Scope.BigqueryInsertdata }, }.FromCertificate(new X509Certificate2(path, certificatePassword, X509KeyStorageFlags.Exportable))); var bigquery = new BigqueryService(new BaseClientService.Initializer { ApplicationName = applicationName, HttpClientInitializer = credential }); return bigquery; }
/// <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="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param> /// <returns></returns> public static WebmastersService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath) { // check the file exists if (!File.Exists(keyFilePath)) { Console.WriteLine("An Error occurred - Key file does not exist"); return null; } string[] scopes = new string[] { WebmastersService.Scope.Webmasters}; // View WebMasters data var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); try { ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); // Create the service. WebmastersService service = new WebmastersService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "WebMasters API Sample", }); return service; } catch (Exception ex) { Console.WriteLine(ex.InnerException); return null; } }
private static void Main(string[] args) { // See the README.md for details of these fields. // Retrieved from https://console.developers.google.com String ServiceAccountEmail = "SERVICE ACCOUNT EMAIL HERE"; String ServiceKeyFilePath = "PATH TO P12 KEYFILE HERE-INCLUDE FILENAME"; String ServiceKeyFilePassword = "******"; // Create a certificate object using the key file. X509Certificate2 certificate = new X509Certificate2(ServiceKeyFilePath, ServiceKeyFilePassword, X509KeyStorageFlags.Exportable); // Use the certificate to create credentials. ServiceAccountCredential oAuth2Credentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(ServiceAccountEmail) { Scopes = new[] { AdExchangeBuyerService.Scope.AdexchangeBuyer } }.FromCertificate(certificate)); // Use the credentials to create a client for the API service. AdExchangeBuyerService buyerService = new AdExchangeBuyerService( new BaseClientService.Initializer { HttpClientInitializer = oAuth2Credentials, ApplicationName = "FirstAPICall" }); // Call the Accounts resource on the service to retrieve a list of // Accounts for the service account AccountsList allAccounts = buyerService.Accounts.List().Execute(); foreach (Account account in allAccounts.Items) { Console.WriteLine("Account id: {0}", account.Id); } Console.ReadLine(); }
public async Task ValidLocallySignedAccessToken_FromX509Certificate() { #if NETSTANDARD const string sPfx = @" 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"; var x509Cert = new X509Certificate2(Convert.FromBase64String(sPfx)); #else const string sPrivateKey = @" -----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALQoMIfUT93VMvb5 4U5dsJLXD1D6z4o/VuVlNUaf5xH01qAv8Egpxe6f5frLB/p1eNyDjNIZ3QitD6aN 9Vfh4ifg6txBuBJtIMfSDvRJITNZ2SjKJREbflZuBk0HINKYQk2H+3TIzUbE/pN4 Cu6Mids5L/oVOnRWIe3bEC+PHR7ZAgMBAAECgYBI1qrwb+2ukeFeK59lcMnQRLVD l3RLv9ohOy80E7h38RbJgzhR5NnK5ck1AduC7vXjqihIVf6g4F+ghmq4knI94KPQ 2fOyQGVV6jVeRVqMusx7tP9V1H26yABiK6TPklcCsWwADFmexfOxfIgbBGSmlbAd N2/ad1Xog1xDebrbEQJBAO+2qSIDX1ahfxUyvvcMaix6Mrh/OYKb5aH1Y/7MfAav lpbQavQHNvak2147aPNxy0ZvWdJ2HVA7hUMkgysYWSUCQQDAZalkZMSrve+Onh55 U+w5xjLklhh8PhYxx8plT8ae9VG75dGvWSz/W81B3ILg2lrNU6o08NKBJdZsJYmc BeKlAkBtJh3zF9gEaTqlW1rqwKNjpyyLJ5r3JqczzLmAXnmmzbLi7vmULejP+5bL XH/YQZtOcgtTMmb8jm2Kegijyc1lAkANGt+e5v4+dIGMxVhuCzlb9hQhXdftHo2E dodivzxYN32Jvu25c+mMu0QP6GVBy53Dvp8pW/36rgkc9LGa3wvBAkEA7dGAl95T UeNFVfuzkYNtQppcSgrx1oTcpTHoNgcvk8AgBf4yDdJJyo0IUONmgJCVffc1aTWn nf/8cW9YC+0icQ== -----END PRIVATE KEY-----"; const string sCert = @" MIICNDCCAZ2gAwIBAgIJAKl3qU1+NsuuMA0GCSqGSIb3DQEBCwUAMDMxCzAJBgNV BAYTAkdCMRMwEQYDVQQIDApTb21lLVN0YXRlMQ8wDQYDVQQKDAZHb29nbGUwHhcN MTYwODEwMTQwOTQ2WhcNNDMxMjI3MTQwOTQ2WjAzMQswCQYDVQQGEwJHQjETMBEG A1UECAwKU29tZS1TdGF0ZTEPMA0GA1UECgwGR29vZ2xlMIGfMA0GCSqGSIb3DQEB AQUAA4GNADCBiQKBgQC0KDCH1E/d1TL2+eFOXbCS1w9Q+s+KP1blZTVGn+cR9Nag L/BIKcXun+X6ywf6dXjcg4zSGd0IrQ+mjfVX4eIn4OrcQbgSbSDH0g70SSEzWdko yiURG35WbgZNByDSmEJNh/t0yM1GxP6TeArujInbOS/6FTp0ViHt2xAvjx0e2QID AQABo1AwTjAdBgNVHQ4EFgQUMqzJi099PA8ML5CV1OSiHgiTGoUwHwYDVR0jBBgw FoAUMqzJi099PA8ML5CV1OSiHgiTGoUwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B AQsFAAOBgQBQ9cMInb2rEcg8TTYq8MjDEegHWLUI9Dq/IvP/FHyKDczza4eX8m+G 3buutN74pX2/GHRgqvqEvvUUuAQUnZ36k6KjTNxfzNLiSXDPNeYmy6PWsUZy4Rye /Van/ePiXdipTKMiUyl7V6dTjkE5p/e372wNVXUpcxOMmYdWmzSMvg=="; var x509Cert = new X509Certificate2(Convert.FromBase64String(sCert)); RSAParameters rsaParameters = Pkcs8.DecodeRsaParameters(sPrivateKey); var privateKey = new System.Security.Cryptography.RSACryptoServiceProvider(); privateKey.ImportParameters(rsaParameters); x509Cert.PrivateKey = privateKey; #endif Assert.That(x509Cert.HasPrivateKey); var initializer = new ServiceAccountCredential.Initializer("some-id") { Clock = new MockClock { UtcNow = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc) } }; var cred = new ServiceAccountCredential(initializer.FromCertificate(x509Cert)); Assert.That(cred.Scopes?.Any(), Is.False); // HasScopes must be false for the type of access token we want to test. string accessToken = await cred.GetAccessTokenForRequestAsync("http://authurl/"); string expectedToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzb21lLWlkIiwic3ViIjoi" + "c29tZS1pZCIsImF1ZCI6Imh0dHA6Ly9hdXRodXJsLyIsImV4cCI6MTQ1MTYxMDAwMCwia" + "WF0IjoxNDUxNjA2NDAwfQ.GfpDHgrFi4ZlGC5LuJEarLU4_eTrT5PVa-S40YtkdB2E1f3" + "4naYG2ItcfBEFg7Gbdkr1cIAyipuhEd2yLfPmWGwhOwVcBRNyK_J5w8RodS44mxNJwau0" + "jKy4x1K20ybLqcnNgzE0wag6fi5GHwdNIB0URdHDTiC88CRYdl1CIdk"; Assert.That(accessToken, Is.EqualTo(expectedToken)); }
public ServiceAccountGoogleCredential(ServiceAccountCredential credential) : base(credential) { }
/// <summary>Creates a <c>GoogleCredential</c> wrapping a <see cref="ServiceAccountCredential"/>.</summary> internal static GoogleCredential FromCredential(ServiceAccountCredential credential) { return(new ServiceAccountGoogleCredential(credential)); }