private async Task <ServiceAccountCredential> Authorize() { var certificate = new X509Certificate2(_keyFilePath, _keyFileSecret, X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(_serviceAccountEmail) { Scopes = new[] { "https://www.googleapis.com/auth/cloudprint" } }.FromCertificate(certificate)); // below is original code //await credential.RequestAccessTokenAsync(CancellationToken.None); #region AHW added switch (_callerType) { case CallingProgramConstants.Console: await credential.RequestAccessTokenAsync(CancellationToken.None); break; case CallingProgramConstants.Desktop: case CallingProgramConstants.Web: case CallingProgramConstants.Service: credential.RequestAccessTokenAsync(CancellationToken.None).Wait(); break; } #endregion return(credential); }
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); }
private async Task CreateCredentials(CancellationToken token, ServiceAccountCredential.Initializer accountInitializer) { var credential = new ServiceAccountCredential(accountInitializer); await credential.RequestAccessTokenAsync(token); _credentials = credential; }
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); }
internal static string CreateGoogleMailService() { // Se obtiene la cuenta de servicio en la consola de google // Leer más : https://developers.google.com/identity/protocols/OAuth2ServiceAccount const string SERVICE_ACCT_EMAIL = "*****@*****.**"; //Generar la llave .p12 en la consola de google en la cuenta de servicios. var certificate = new X509Certificate2(@"C:\inetpub\wwwroot\mariscal.p12", "notasecret", X509KeyStorageFlags.Exportable); var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(SERVICE_ACCT_EMAIL) { User = "******", // Muy importante, darle permiso a la cuenta de servicio el acceso a las aplicaciones de gmail Scopes = new[] { "https://mail.google.com/", "https://www.googleapis.com/auth/gmail.modify", "https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.metadata" } //Aqui aunque se establece el scope igual en las cuentas de servico se debe realizar... }.FromCertificate(certificate); var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer); if (!credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result) { throw new InvalidOperationException("Access token failed."); } return(credential.Token.AccessToken); }
private static SpreadsheetsService GetUserCredential() { SpreadsheetsService sheetService = null; try { string currentAssembly = System.Reflection.Assembly.GetExecutingAssembly().Location; string currentDirectory = System.IO.Path.GetDirectoryName(currentAssembly); string keyFilePath = System.IO.Path.Combine(currentDirectory, "Resources\\" + keyFile); var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { "https://spreadsheets.google.com/feeds/" } }.FromCertificate(certificate)); credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait(); var requestFactory = new GDataRequestFactory("My App User Agent"); requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken)); sheetService = new SpreadsheetsService("HOK Project Replicator"); sheetService.RequestFactory = requestFactory; } catch (Exception ex) { MessageBox.Show("Failed to get user credential.\n" + ex.Message, "Google Spreadsheet : User Credential", MessageBoxButton.OK, MessageBoxImage.Warning); } return(sheetService); }
/// <summary> /// Authorizes the specified json credential file path. /// </summary> /// <param name="jsonCredentialPath">The json credential.</param> /// <returns></returns> /// <exception cref="InvalidOperationException">JSON content does not represent valid service account credentials</exception> private ServiceAccountCredential Authorize(string jsonCredential) { string[] scopes = { "https://www.googleapis.com/auth/cloudprint" }; var credentialParameters = NewtonsoftJsonSerializer.Instance.Deserialize <JsonCredentialParameters>(jsonCredential); if (credentialParameters.Type != "service_account" || string.IsNullOrEmpty(credentialParameters.ClientEmail) || string.IsNullOrEmpty(credentialParameters.PrivateKey)) { throw new InvalidOperationException("JSON content does not represent valid service account credentials."); } _serviceAccountEmail = credentialParameters.ClientEmail; var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail) { Scopes = scopes }.FromPrivateKey(credentialParameters.PrivateKey)); // this does the magic for webform that need sync results and fails with async execution credential.RequestAccessTokenAsync(CancellationToken.None).Wait(); return(credential); }
public static GmailService InitilzeServiceByServiceAccount() { try { var json = System.IO.File.ReadAllText(_serviceAccountKey); var cred = JsonConvert.DeserializeObject <ServiceAccountCred>(json); GmailService service = new GmailService(); var saCredential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cred.client_email) { Scopes = new[] { GmailService.Scope.GmailModify }, User = _serviceAccountUser }.FromPrivateKey(cred.private_key)); if (saCredential.RequestAccessTokenAsync(CancellationToken.None).Result) { var initilizer = new BaseClientService.Initializer() { HttpClientInitializer = saCredential, }; Google.Apis.Auth.OAuth2.Responses.TokenResponse toke = saCredential.Token; service = new GmailService(initilizer); } return(service); } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); return(null); } }
private async Task <ServiceAccountCredential> AuthorizeAsync(string jsonCredentialPath) { string[] scopes = { GoogleCloudPrintScope }; using (var stream = new FileStream(jsonCredentialPath, FileMode.Open, FileAccess.Read)) { var credentialParameters = NewtonsoftJsonSerializer.Instance.Deserialize <JsonCredentialParameters>(stream); if (credentialParameters.Type != "service_account" || string.IsNullOrEmpty(credentialParameters.ClientEmail) || string.IsNullOrEmpty(credentialParameters.PrivateKey)) { throw new InvalidOperationException("JSON content does not represent valid service account credentials."); } var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail) { Scopes = scopes }.FromPrivateKey(credentialParameters.PrivateKey)); // this does the magic for webform that need sync results and fails with async execution await credential.RequestAccessTokenAsync(CancellationToken.None); return(credential); } }
// GET: Analytics public ActionResult Index() { //自己service 版本 //將自己的驗證json檔放到app_data string[] scopes = new string[] { AnalyticsService.Scope.AnalyticsReadonly }; // view and manage your Google Analytics data var keyFilePath = HttpContext.Server.MapPath("~/App_Data/6c7504a5781f.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)); //取得token string AuthenticationKey = ""; if (credential.RequestAccessTokenAsync(CancellationToken.None).Result) { AuthenticationKey = credential.Token.AccessToken; } ViewBag.auth = AuthenticationKey; return View(); }
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); }
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(); } }
private async void Enviar(string correoDestinatario, string nombreDestinatario, string asunto, string cuerpo) { string nombreAplicacion = _configuration.GetValue <string>("Correo:NombreAplicacion"); string muroAgilEmail = _configuration.GetValue <string>("Correo:Direccion"); 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"); 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(muroAgilEmail, muroAgilNombre, Encoding.UTF8); MailAddress toAddress = new MailAddress(correoDestinatario, nombreDestinatario, Encoding.UTF8); MailMessage message = new MailMessage(fromAddress, toAddress) { Subject = asunto, Body = cuerpo, 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 = Convert.ToBase64String(stream.ToArray()) .Replace("+", "-") .Replace("/", "_") .Replace("=", ""); service.Users.Messages.Send(new Message { Raw = rawMessage }, muroAgilEmail).Execute(); } }
private async Task RefreshAccessTokenAsync() { if (_credentials == null) { _credentials = !string.IsNullOrEmpty(_jsonCredencialFilePath) ? await AuthorizeAsync(_jsonCredencialFilePath) : await AuthorizeAsync(); } if (_credentials.Token.IsExpired(_credentials.Clock)) { await _credentials.RequestAccessTokenAsync(CancellationToken.None); } }
private async Task <string> GetToken() { if (_serviceAccountCredential.Token != null && !_serviceAccountCredential.Token.IsExpired(_serviceAccountCredential.Clock)) { return(_serviceAccountCredential.Token.AccessToken); } if (await _serviceAccountCredential.RequestAccessTokenAsync(new CancellationToken())) { return(_serviceAccountCredential.Token.AccessToken); } throw new FcmApiException(FirebaseCloudMessagingApiConstants.TokenError); }
private ServiceAccountCredential Authorize() { var certificate = new X509Certificate2(_keyFilePath, _keyFileSecret, X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(_serviceAccountEmail) { Scopes = new[] { "https://www.googleapis.com/auth/cloudprint" } }.FromCertificate(certificate)); credential.RequestAccessTokenAsync(CancellationToken.None).Wait(); return(credential); }
/// <summary> /// Gets Service Authorization for application. Service authorization allows /// API calls without user interaction. /// </summary> /// <param name="certificate">certificate (loaded from .p12 file) which you can get on Google developers console</param> public virtual void ServiceAuthorize(X509Certificate2 certificate) { var sac = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(Mail) { Scopes = Scopes }.FromCertificate(certificate)); var cts = new CancellationToken(); var response = sac.RequestAccessTokenAsync(cts).Result; if (!response) { throw new UnauthorizedAccessException("Could not authorize service account!"); } ServiceAccount = sac; }
private async Task <ServiceAccountCredential> AuthorizeAsync() { using (var certificate = GetCertificate()) { var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(_serviceAccountEmail) { Scopes = new[] { GoogleCloudPrintScope } }.FromCertificate(certificate)); await credential.RequestAccessTokenAsync(CancellationToken.None); return(credential); } }
public async Task <bool> RequestAccessTokenAsync() { var certificate = new X509Certificate2(_certificateFile, "notasecret", X509KeyStorageFlags.Exportable); var serviceAccountCredential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(_serviceAccount) { Scopes = new[] { _defaultScope } }.FromCertificate(certificate)); var status = await serviceAccountCredential.RequestAccessTokenAsync(CancellationToken.None); if (status) { AccessToken = serviceAccountCredential.Token.AccessToken; } return(status); }
private async Task <Boolean> Authorize(CancellationToken token = default) { if (_credentials == null) { throw new NotAuthenticatedException(); } if (!_credentials.Token.IsExpired(_credentials.Clock)) { return(false); } await _credentials.RequestAccessTokenAsync(token); return(true); }
private async Task <bool> AddAuthClaims(TokenValidatedContext context) { // should never be null or not a JwtSecurityToken if (context.SecurityToken is JwtSecurityToken token) { // Get the usersId from JWT string userId = token.Payload["user_id"].ToString(); if (context.Principal.Identity is ClaimsIdentity identity) { // Check if credential or token is null or is the token is expired or expiring if (credential == null || credential.Token == null || credential.Clock == null || credential.Token.IsExpired(credential.Clock)) { // Get access token for database using private key credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(Config["Firebase:client_email"]) { Scopes = scopes }.FromPrivateKey(Config["Firebase:private_key"]) ); // Retrieving Token from credentials async. // Why do I assign to task? // What does CancellationToken.None do var task = await credential.RequestAccessTokenAsync(CancellationToken.None); } if (credential != null && credential.Token != null && credential.Clock != null && !credential.Token.IsExpired(credential.Clock)) { // Get access token from creds string accessToken = credential.Token.AccessToken; // Add Auth Claims await AddRoleClaims(identity, accessToken, userId); } else { // Should not get here // creds are bad or token is expired even after a refresh check } // Add Auth role claim regardless of admin status identity.AddClaim(new Claim(ClaimTypes.Role, "Auth")); return(true); } } return(false); }
/// <summary> /// /// </summary> /// <param name="p12FilePath"></param> /// <param name="user">"*****@*****.**"</param> /// <param name="pwd"></param> /// <param name="scopes"></param> static public IConfigurableHttpClientInitializer LoadCredentialFromP12(string p12FilePath, string user, string pwd = null, string[] scopes = null) { string password = (pwd == null) ? "notasecret" : pwd; var certificate = new X509Certificate2(p12FilePath, password, X509KeyStorageFlags.Exportable); var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(user) { Scopes = scopes ?? defaultScopes }.FromCertificate(certificate); var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer); if (!credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result) { throw new InvalidOperationException("Access token request failed."); } return(credential); }
// GET: Admin public ActionResult Stats() { string credPath = Server.MapPath("~/Content/PhongDaoTao-Book-1818d16b5e2f.json"); var json = System.IO.File.ReadAllText(credPath); Newtonsoft.Json.Linq.JObject cr = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(json); // "personal" service account credential // Create an explicit ServiceAccountCredential credential var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer((string)cr.GetValue("client_email")) { Scopes = new[] { "https://www.googleapis.com/auth/analytics.readonly" } }.FromPrivateKey((string)cr.GetValue("private_key"))); bool status = xCred.RequestAccessTokenAsync(CancellationToken.None).Result; ViewBag.GAAccessToken = xCred.Token.AccessToken; return(View()); }
public static async void Main(string[] args) { var certificate = new X509Certificate2(@"C:\path\to\certificate.p12", "password", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential .Initializer("*****@*****.**") { // Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes Scopes = new[] { "https://mail.google.com/" }, User = "******" }.FromCertificate(certificate)); // Note: result will be true if the access token was received successfully bool result = await credential.RequestAccessTokenAsync(CancellationToken.None); if (!result) { Console.WriteLine("Error fetching access token!"); return; } var message = new MimeMessage(); message.From.Add(new MailboxAddress("Your Name", "*****@*****.**")); message.To.Add(new MailboxAddress("Recipient's Name", "*****@*****.**")); message.Subject = "This is a test message"; var builder = new BodyBuilder(); builder.TextBody = "This is the body of the message."; builder.Attachments.Add(@"C:\path\to\attachment"); message.Body = builder.ToMessageBody(); using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls); // use the access token as the password string client.Authenticate("*****@*****.**", credential.Token.AccessToken); client.Send(message); client.Disconnect(true); } }
private void Login() { var keyPath = Path.Combine(Environment.CurrentDirectory, "key.p12"); var certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/firebase.database" } } .FromCertificate(certificate)); ServiceAccountCredential = credential; ServiceAccountCredential.RequestAccessTokenAsync(new System.Threading.CancellationToken()).Wait(); }
public void Credential() { var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(GSUIT_CLIENT_ACCOUNT) { User = UserEmail, Scopes = Scopes }.FromPrivateKey(GSUIT_CLIENT_PRIVATEKEY)); if (credential.RequestAccessTokenAsync(CancellationToken.None).Result) { service = new GmailService( new Google.Apis.Services.BaseClientService.Initializer() { ApplicationName = "Punnel", HttpClientInitializer = credential } ); } }
private void oAuth2() { //euHReka string keyFilePath = Path.Combine(Environment.CurrentDirectory, @"..\..\Key.p12"); // found in developer console //string keyFilePath = @"D:\PEX\PEX_ALM_JENKINS_INTEGRATION\ALM_JENKINS_INTEGRATION\Key.p12"; // found in developer console string serviceAccountEmail = "*****@*****.**"; // found in developer console var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); //create credential using certificate ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { "https://spreadsheets.google.com/feeds/" } //this scopr is for spreadsheets, check google scope FAQ for others }.FromCertificate(certificate)); credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait(); //request token var requestFactory = new GDataRequestFactory("AlmJenkinsIntegration"); requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken)); spreadsheetsService.RequestFactory = requestFactory; //add new request factory to your old service }
private async Task SendEmail(MimeMessage message) { var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes, User = streamworkEmailAddress }.FromCertificate(new X509Certificate2(certificatePath, privateKeyPassword, X509KeyStorageFlags.MachineKeySet))); // Token gets put inside credential. At least cross your f*****g fingers that it does. await credential.RequestAccessTokenAsync(CancellationToken.None); using var client = new SmtpClient(); client.Connect(gmailSmtp, gmailPort); var oauth2 = new SaslMechanismOAuth2(streamworkEmailAddress, credential.Token.AccessToken); client.Authenticate(oauth2); client.Send(message); client.Disconnect(true); }
protected OptionsWrapper <MkSmtpMailerSettings> SetupMailerOptionsToken() { var certificate = new X509Certificate2(@"C:\Users\steph\Downloads\NullMailerTests-ec989cf935fc.p12", "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer("*****@*****.**") { // Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes Scopes = new[] { "https://mail.google.com/" }, User = "******" }.FromCertificate(certificate)); var result = credential.RequestAccessTokenAsync(CancellationToken.None).Result; return(new OptionsWrapper <MkSmtpMailerSettings>( new MkSmtpMailerSettings { FromDisplayName = "xunit", FromEmailAddress = "*****@*****.**", SmtpServer = "smtp.gmail.com", SmtpPort = 465, SmtpRequireSsl = true, AuthenticationSettings = new MkSmtpAuthenticationSettings { Authenticator = new MkSmtpAccessTokenAuthenticator { AccessTokenFactory = () => credential.Token.AccessToken, UserName = "******" } }, TemplateSettings = new MkFileTemplateSettings { TemplatePath = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, @"..\..\..\..\TestData\templates")) } })); }
public BESGoogleContactsService() { var certificate = new X509Certificate2(serviceAccountCertPath, serviceAccountCertPassword, X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { "https://www.google.com/m8/feeds/" }, User = Email }.FromCertificate(certificate)); bool success = credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result; RequestSettings settings = new RequestSettings("Google Sync.", credential.Token.AccessToken) { AutoPaging = true, UseSSL = true }; ContactsRequest cr = new ContactsRequest(settings); PrintAllContacts(cr); }