public virtual ClientSecret FindSecret([NotNull] string value, string type = IdentityServerConstants.SecretTypes.SharedSecret) { return(ClientSecrets.FirstOrDefault(s => s.Type == type && s.Value == value)); }
/// <summary> /// The main entry point for the application. /// </summary> public static void Main(string[] args) { Console.WriteLine("This application generates an OAuth2 refresh token for use with " + "the Google Ads API .NET client library. To use this application\n" + "1) Follow the instructions on https://developers.google.com/adwords/api/docs/" + "guides/authentication#create_a_client_id_and_client_secret to generate a new " + "client ID and secret.\n2) Enter the client ID and client Secret when prompted.\n" + "3) Once the output is generated, copy its contents into your " + "App.config file.\n\n"); // Accept the client ID from user. Console.Write("Enter the client ID: "); string clientId = Console.ReadLine(); // Accept the client ID from user. Console.Write("Enter the client secret: "); string clientSecret = Console.ReadLine(); // Should API scopes include AdWords API? string useAdWordsApiScope = AcceptInputWithLimitedOptions( "Authenticate for AdWords API?", new string[] { "yes", "no" }); // Should API scopes include AdWords API? string useAdManagerApiScope = AcceptInputWithLimitedOptions("Authenticate for Ad Manager API?", new string[] { "yes", "no" }); // Accept any additional scopes. Console.Write("Enter additional OAuth2 scopes to authenticate for (space separated): "); string additionalScopes = Console.ReadLine(); List <string> scopes = new List <string>(); if (useAdWordsApiScope.ToLower().Trim() == "yes") { scopes.Add(ADWORDS_API_SCOPE); } if (useAdManagerApiScope.ToLower().Trim() == "yes") { scopes.Add(AD_MANAGER_API_SCOPE); } scopes.AddRange(additionalScopes.Split(' ').Select(s => s.Trim()) .Where(s => !string.IsNullOrEmpty(s))); // Load the JSON secrets. ClientSecrets secrets = new ClientSecrets() { ClientId = clientId, ClientSecret = clientSecret }; try { // Authorize the user using installed application flow. Task <UserCredential> task = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scopes, String.Empty, CancellationToken.None, new NullDataStore()); task.Wait(); UserCredential credential = task.Result; Console.WriteLine("\nCopy the following content into your App.config file.\n\n" + $"<add key = 'OAuth2Mode' value = 'APPLICATION' />\n" + $"<add key = 'OAuth2ClientId' value = '{clientId}' />\n" + $"<add key = 'OAuth2ClientSecret' value = '{clientSecret}' />\n" + $"<add key = 'OAuth2RefreshToken' " + $"value = '{credential.Token.RefreshToken}' />\n"); Console.WriteLine("Press <Enter> to continue..."); Console.ReadLine(); } catch (AggregateException) { Console.WriteLine("An error occured while authorizing the user."); } }
public virtual void AddSecret([NotNull] string value, DateTime?expiration = null, string type = IdentityServerConstants.SecretTypes.SharedSecret, string description = null) { ClientSecrets.Add(new ClientSecret(Id, value, expiration, type, description)); }
public virtual void RemoveSecret([NotNull] string value, string type = IdentityServerConstants.SecretTypes.SharedSecret) { ClientSecrets.RemoveAll(s => s.Value == value && s.Type == type); }
private async Task <UserCredential> GetCalendarCredential(string key, string[] scopes, ClientSecrets gsec) { try { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = gsec, Scopes = scopes }; initializer.DataStore = new FileDataStore("OAuth", true); var flow = new GoogleAuthorizationCodeFlow(initializer); var token = await initializer.DataStore.GetAsync <TokenResponse>(key); if (token == null) { var result = await AuthorizeAsync(initializer, key); return(new UserCredential(result.Flow, key, result.Token)); } return(new UserCredential(flow, key, token)); } catch (Exception ex) { System.IO.File.WriteAllText("error.txt", ex.Message); return(null); } }
/// <summary> /// Returns true if Oauth2ClientSubmit instances are equal /// </summary> /// <param name="other">Instance of Oauth2ClientSubmit to be compared</param> /// <returns>Boolean</returns> public bool Equals(Oauth2ClientSubmit other) { if (other is null) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( ClientId == other.ClientId || ClientId != null && ClientId.Equals(other.ClientId) ) && ( Name == other.Name || Name != null && Name.Equals(other.Name) ) && ( AllowedGrantTypes == other.AllowedGrantTypes || AllowedGrantTypes != null && other.AllowedGrantTypes != null && AllowedGrantTypes.SequenceEqual(other.AllowedGrantTypes) ) && ( RedirectUris == other.RedirectUris || RedirectUris != null && other.RedirectUris != null && RedirectUris.SequenceEqual(other.RedirectUris) ) && ( AllowedCorsOrigins == other.AllowedCorsOrigins || AllowedCorsOrigins != null && other.AllowedCorsOrigins != null && AllowedCorsOrigins.SequenceEqual(other.AllowedCorsOrigins) ) && ( PostLogoutRedirectUris == other.PostLogoutRedirectUris || PostLogoutRedirectUris != null && other.PostLogoutRedirectUris != null && PostLogoutRedirectUris.SequenceEqual(other.PostLogoutRedirectUris) ) && ( AllowedScopes == other.AllowedScopes || AllowedScopes != null && other.AllowedScopes != null && AllowedScopes.SequenceEqual(other.AllowedScopes) ) && ( ClientSecrets == other.ClientSecrets || ClientSecrets != null && other.ClientSecrets != null && ClientSecrets.SequenceEqual(other.ClientSecrets) ) && ( HashedClientSecrets == other.HashedClientSecrets || HashedClientSecrets != null && other.HashedClientSecrets != null && HashedClientSecrets.SequenceEqual(other.HashedClientSecrets) ) && ( AllowedOfflineAccess == other.AllowedOfflineAccess || AllowedOfflineAccess.Equals(other.AllowedOfflineAccess) )); }
public virtual void RemoveAllSecrets() { ClientSecrets.Clear(); }
/// <summary>Creates an authorization code flow with the given parameters.</summary> /// <param name="dataStore">The data store.</param> /// <param name="scopes">The Scopes.</param> /// <param name="httpClientFactory">The HTTP client factory. If not set the default will be used.</param> /// <returns>Authorization code flow</returns> private AuthorizationCodeFlow CreateFlow(IDataStore dataStore = null, IEnumerable<string> scopes = null, IHttpClientFactory httpClientFactory = null) { var secrets = new ClientSecrets() { ClientId = "id", ClientSecret = "secret" }; var initializer = new AuthorizationCodeFlow.Initializer(AuthorizationCodeUrl, TokenUrl) { ClientSecrets = secrets, HttpClientFactory = httpClientFactory }; if (dataStore != null) { initializer.DataStore = dataStore; } if (scopes != null) { initializer.Scopes = scopes; } return new AuthorizationCodeFlow(initializer); }
public async Task <bool> LoginAsync() { if (_options is null) { throw new ArgumentNullException($"{nameof(GooglePhotosOptions)} cannot be null!"); } if (string.IsNullOrWhiteSpace(_options.User)) { throw new ArgumentNullException($"{nameof(GooglePhotosOptions)}.{nameof(_options.User)} cannot be null!"); } if (string.IsNullOrWhiteSpace(_options.ClientId)) { throw new ArgumentNullException($"{nameof(GooglePhotosOptions)}.{nameof(_options.ClientId)} cannot be null!"); } if (string.IsNullOrWhiteSpace(_options.ClientSecret)) { throw new ArgumentNullException($"{nameof(GooglePhotosOptions)}.{nameof(_options.ClientSecret)} cannot be null!"); } if (_options.Scopes.IsNullOrEmpty()) { throw new ArgumentNullException($"{nameof(GooglePhotosOptions)}.{nameof(_options.Scopes)} cannot be null/empty!"); } var secrets = new ClientSecrets { ClientId = _options.ClientId, ClientSecret = _options.ClientSecret }; FileDataStore?dataStore = null; if (!string.IsNullOrWhiteSpace(_options.FileDataStoreFullPathOverride)) { dataStore = new FileDataStore(_options.FileDataStoreFullPathOverride, true); } _logger.LogDebug($"Requesting authorization..."); var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( secrets, GetScopes(), _options.User, CancellationToken.None, dataStore); _logger.LogDebug("Authorisation granted or not required (if the saved access token already available)"); if (credential.Token.IsExpired(credential.Flow.Clock)) { _logger.LogWarning("The access token has expired, refreshing it"); if (await credential.RefreshTokenAsync(CancellationToken.None)) { _logger.LogInformation("The access token is now refreshed"); } else { _logger.LogError("The access token has expired but we can't refresh it :("); return(false); } } else { _logger.LogDebug("The access token is OK, continue"); } _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(credential.Token.TokenType, credential.Token.AccessToken); return(true); string[] GetScopes()//todo: make extension method to convert any enum to string[] and move to CasCap.Common.Extensions { var l = new List <string>(_options.Scopes.Length); foreach (var scope in _options.Scopes) { if (dScopes.TryGetValue(scope, out var s)) { l.Add(s); } } return(l.ToArray()); } }
public GoogleDriveService(ClientSecrets applicationCredentials, string applicationName) { _applicationCredentials = applicationCredentials; _applicationName = applicationName; }
/// <summary> /// /// </summary> /// <param name="virtualPath"></param> /// <param name="queryString"></param> /// <param name="options"></param> /// <param name="urlParts"></param> /// <param name="apiTokens"></param> /// <param name="clientSecrets"></param> /// <param name="virtualPathArgs"></param> /// <returns></returns> public static Stream GetStream(string virtualPath, string queryString, RequestOptions options, UrlParts urlParts, Tokens apiTokens, ClientSecrets clientSecrets, params object[] virtualPathArgs) { if (options == null) { options = new RequestOptions(); } options.PrepForRequest(); CleanupVirtualPathArgs(virtualPathArgs); string url = CreateUrl(urlParts, string.Format(virtualPath, virtualPathArgs), options.GetQueryString(queryString), options.Fields, options.Expand); WebRequest httpWebRequest = WebRequest.Create(url); httpWebRequest.Method = "Get"; httpWebRequest.Headers.Add("Authorization", "Bearer " + apiTokens.AccessToken); var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); Stream stream = httpResponse.GetResponseStream(); return stream; }
/// <summary> /// /// </summary> /// <param name="virtualPath"></param> /// <param name="queryString"></param> /// <param name="options"></param> /// <param name="urlParts"></param> /// <param name="apiTokens"></param> /// <param name="clientSecrets"></param> /// <param name="virtualPathArgs"></param> /// <returns></returns> public static Stream GetStream(string virtualPath, string queryString, RequestOptions options, UrlParts urlParts, Tokens apiTokens, ClientSecrets clientSecrets, params object[] virtualPathArgs) { if (options == null) { options = new RequestOptions(); } options.PrepForRequest(); CleanupVirtualPathArgs(virtualPathArgs); string url = CreateUrl(urlParts, string.Format(virtualPath, virtualPathArgs), options.GetQueryString(queryString), options.Fields, options.Expand); WebRequest httpWebRequest = WebRequest.Create(url); httpWebRequest.Method = "Get"; httpWebRequest.Headers.Add("Authorization", "Bearer " + apiTokens.AccessToken); var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); Stream stream = httpResponse.GetResponseStream(); return(stream); }
public static void Main(string[] args) { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler); string dataPath = GetLocalAppDataPath(); string MBoxViewerPath = Path.Combine(dataPath, "MBoxViewer"); string MailServicePath = Path.Combine(MBoxViewerPath, "MailService"); string TempPath = Path.Combine(MailServicePath, "Temp"); string okFilePath = MailServicePath + "\\ForwardMailSuccess.txt"; string errorFilePath = MailServicePath + "\\ForwardMailError.txt"; string errorFilePathOldInstance = MailServicePath + "\\ForwardMailError2.txt"; System.IO.DirectoryInfo info = Directory.CreateDirectory(TempPath); string loggerFilePath = FindKeyinArgs(args, "--logger-file"); var logger = new FileLogger(); logger.Open(loggerFilePath); logger.Log("Logger Open"); try { // File.Delete doesn't seem to generate exceptions if file doesn't exist //if (File.Exists(okFilePath) File.Delete(okFilePath); //if (File.Exists(errorFilePath) File.Delete(errorFilePath); File.Delete(errorFilePathOldInstance); } catch (Exception ex) { string txt = String.Format("Delete Critical Files Failed\n{0}\n{1}\n{2}\n\n{3}", okFilePath, errorFilePath, errorFilePathOldInstance, ex.Message); bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, txt); logger.Log("Exception in Delete Critical Files: ", ex.ToString()); System.Environment.Exit(ExitCodes.ExitMailAddress); } int numArgs = args.GetLength(0); if ((numArgs <= 0) || ((numArgs % 2) != 0)) { string errorText = String.Format("Invalid command argument list: {0} .", String.Join(" ", args)); bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n"); logger.Log(errorText); System.Environment.Exit(ExitCodes.ExitCmdArguments); } /* * if (numArgs <= 0) * { * logger.Log(@"Usage: --from addr --to addr1,addr2,.. --cc addr1,addr2,.. -bcc addr1,addr2,.. * --user login-user-name --passwd --login-user-password --smtp smtp-server-name", ""); * Debug.Assert(true == false); * System.Environment.Exit(1); * } */ string instance = ""; IniFile smtpIni = null; EMailInfo mailInfo = new EMailInfo(); SMTPConfig smtpConfig = new SMTPConfig(); string smtpConfigFilePath = ""; string UserPassword = ""; string protocolLoggerFilePath = ""; int tcpListenPort = 0; logger.Log("Command line argument list:"); for (int j = 0, i = 0; j < numArgs; j = j + 2, i++) { string key = args[j]; string val = args[j + 1]; if (!key.StartsWith("--")) { string errorText = String.Format("Invalid key: {0} ", key); bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n"); logger.Log(errorText); System.Environment.Exit(ExitCodes.ExitCmdArguments); } if ((j + 1) >= numArgs) { string errorText = String.Format("Found key: {0} without value.", key); bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n"); logger.Log(errorText); System.Environment.Exit(ExitCodes.ExitCmdArguments); } if (key.CompareTo("--instance-id") == 0) { instance = val; } else if (key.CompareTo("--smtp-protocol-logger") == 0) { protocolLoggerFilePath = val; } else if (key.CompareTo("--from") == 0) { mailInfo.From = val; } else if (key.CompareTo("--to") == 0) { mailInfo.To = val; } else if (key.CompareTo("--cc") == 0) { mailInfo.CC = val; } else if (key.CompareTo("--bcc") == 0) { mailInfo.BCC = val; } else if (key.CompareTo("--user") == 0) { mailInfo.To = val; } else if (key.CompareTo("--passwd") == 0) { UserPassword = val; } else if (key.CompareTo("--smtp-cnf") == 0) { smtpConfigFilePath = val; } else if (key.CompareTo("--tcp-port") == 0) { tcpListenPort = int.Parse(val); } else if (key.CompareTo("--eml-file") == 0) { mailInfo.EmlFilePath = val; } else if (key.CompareTo("--mail-text-file") == 0) { mailInfo.TextFilePath = val; } else if (key.CompareTo("--logger-file") == 0) { ; // see FindKeyinArgs(args, "--logger-file"); } else { logger.Log(String.Format(" Unknown Key: {0} {1}", args[j], args[j + 1])); } logger.Log(String.Format(" {0} {1}", args[j], args[j + 1])); } if (smtpConfigFilePath.Length == 0) { string errorText = String.Format("required --smtp-cnf command line argument missing."); bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n"); logger.Log(errorText); System.Environment.Exit(ExitCodes.ExitCmdArguments); } if (!File.Exists(smtpConfigFilePath)) { string errorText = String.Format("SMTP configuration file {0} doesn't exist.", smtpConfigFilePath); bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n"); logger.Log(errorText); System.Environment.Exit(ExitCodes.ExitCmdArguments); } try { if (protocolLoggerFilePath.Length > 0) { File.Delete(protocolLoggerFilePath); } } catch (Exception /*ex*/) {; } // ignore smtpIni = new IniFile(smtpConfigFilePath); string ActiveMailService = smtpIni.IniReadValue("MailService", "ActiveMailService"); smtpConfig.MailServiceName = smtpIni.IniReadValue(ActiveMailService, "MailServiceName"); smtpConfig.SmtpServerAddress = smtpIni.IniReadValue(ActiveMailService, "SmtpServerAddress"); smtpConfig.SmtpServerPort = int.Parse(smtpIni.IniReadValue(ActiveMailService, "SmtpServerPort")); smtpConfig.UserAccount = smtpIni.IniReadValue(ActiveMailService, "UserAccount"); if (UserPassword.Length > 0) { smtpConfig.UserPassword = UserPassword; } else { smtpConfig.UserPassword = smtpIni.IniReadValue(ActiveMailService, "UserPassword"); } smtpConfig.EncryptionType = int.Parse(smtpIni.IniReadValue(ActiveMailService, "EncryptionType")); logger.Log(smtpConfig.ToString()); // Uncomment when you exec this application from MBoxViewer //smtpConfig.UserPassword = ""; if (smtpConfig.UserPassword.Length == 0) { logger.Log("Waiting to receive password"); smtpConfig.UserPassword = WaitForPassword(tcpListenPort, logger, errorFilePath); if (smtpConfig.UserPassword.Length > 0) { logger.Log("Received non empty password"); //logger.Log("Received non empty password: "******"Received empty password"); } int found = smtpConfig.UserPassword.IndexOf(":"); if (found <= 0) { // Old instance , log to differnt file bool rval = FileUtils.CreateWriteCloseFile(errorFilePathOldInstance, "Received invalid id:password. Exitting\n"); System.Environment.Exit(ExitCodes.ExitCmdArguments); } string id = smtpConfig.UserPassword.Substring(0, found); string passwd = smtpConfig.UserPassword.Substring(found + 1); smtpConfig.UserPassword = passwd; logger.Log("Command line instance id: ", instance); logger.Log("Received instance id: ", id); //logger.Log("Received password: "******"Received password: "******"xxxxxxxxxxxx"); if (id.CompareTo(instance) != 0) { // Old instance , log to different file bool rval = FileUtils.CreateWriteCloseFile(errorFilePathOldInstance, "This is old instance. Exitting\n"); System.Environment.Exit(ExitCodes.ExitCmdArguments); } } MimeKit.ParserOptions opt = new MimeKit.ParserOptions(); var From = new MailboxAddress("", smtpConfig.UserAccount); // InternetAddressList CCList = new InternetAddressList(); InternetAddressList BCCList = new InternetAddressList(); InternetAddressList ToList = new InternetAddressList(); try { if (mailInfo.To.Length > 0) { ToList = MimeKit.InternetAddressList.Parse(opt, mailInfo.To); } if (mailInfo.CC.Length > 0) { CCList = MimeKit.InternetAddressList.Parse(opt, mailInfo.CC); } if (mailInfo.BCC.Length > 0) { BCCList = MimeKit.InternetAddressList.Parse(opt, mailInfo.BCC); } } catch (Exception ex) { bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Parsing Internet Address list Failed\n", ex.Message); logger.Log("Exception in InternetAddressList.Parse: ", ex.ToString()); System.Environment.Exit(ExitCodes.ExitMailAddress); } // string emlFilePath = mailInfo.EmlFilePath; // create the main textual body of the message var text = new TextPart("plain"); try { text.Text = File.ReadAllText(mailInfo.TextFilePath, Encoding.UTF8); } catch (Exception ex) { bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Building Mime Mesage Failed\n", ex.Message); logger.Log("Exception in Building Mime Message: ", ex.ToString()); System.Environment.Exit(ExitCodes.ExitMimeMessage); } logger.Log("Forwarding Eml file:", emlFilePath); MimeMessage msg = null; try { var message = new MimeMessage(); message = MimeKit.MimeMessage.Load(emlFilePath); List <MimeMessage> mimeMessages = new List <MimeMessage>(); mimeMessages.Add(message); msg = BuildMimeMessageWithEmlAsRFC822Attachment(text, mimeMessages, From, ToList, CCList, BCCList); } catch (Exception ex) { bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Building Mime Mesage Failed\n", ex.Message); logger.Log("Exception in Building Mime Message: ", ex.ToString()); System.Environment.Exit(ExitCodes.ExitMimeMessage); } logger.Log("BuildMimeMessageWithEmlAsRFC822Attachment Done"); //string msgAsString = MailkitConvert.ToString(msg); //string msgAsString = msg.ToString(); //logger.Log("\n", msgAsString); // OAUTH2 works on Google but requires verification by Google and it seems to be chargable option if number of users > 100 // Another problem is that ClientSecret can't be hardcoded in the application // For now we will just rely on User Account and User Password for authentication SaslMechanism oauth2 = null;; bool useOAUTH2 = false; if (useOAUTH2) { string appClientId = "xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"; string appClientSecret = "yyyyyyyyyyyyyyyyyyyyyyyyyyy"; var accessScopes = new[] { // that is the only scope that works per info from jstedfast "https://mail.google.com/", }; var clientSecrets = new ClientSecrets { ClientId = appClientId, ClientSecret = appClientSecret }; oauth2 = GetAuth2Token(smtpConfig.UserAccount, clientSecrets, accessScopes); } IProtocolLogger smtpProtocolLogger = null; if (protocolLoggerFilePath.Length > 0) { smtpProtocolLogger = new ProtocolLogger(protocolLoggerFilePath); } else { smtpProtocolLogger = new NullProtocolLogger(); } using (var client = new SmtpClient(smtpProtocolLogger)) { try { client.Connect(smtpConfig.SmtpServerAddress, smtpConfig.SmtpServerPort, (SecureSocketOptions)smtpConfig.EncryptionType); } catch (Exception ex) { bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Connect to SMTP Server Failed\n", ex.Message); logger.Log("Exception in Connect: ", ex.ToString()); System.Environment.Exit(ExitCodes.ExitConnect); } logger.Log(String.Format("Connected to {0} mail service", smtpConfig.MailServiceName)); try { if (useOAUTH2) { client.Authenticate(oauth2); } else { client.Authenticate(smtpConfig.UserAccount, smtpConfig.UserPassword); } } catch (Exception ex) { bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "SMTP Authentication Failed\n", ex.Message); logger.Log("Exception in Authenticate: ", ex.ToString()); System.Environment.Exit(ExitCodes.ExitAuthenticate); } logger.Log("SMTP Authentication Succeeded"); // Clear smtpConfig.UserPassword in case it cores smtpConfig.UserPassword = ""; try { client.Send(msg); } catch (Exception ex) { bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Send Failed\n", ex.Message); logger.Log("Exception in Send to SMTP Server: ", ex.ToString()); //string msgString = MailkitConvert.ToString(msg); //string msgAsString = msg.ToString(); // To help to investigate Warning place at the begining of the serialized MimeMessage // X - MimeKit - Warning: Do NOT use ToString() to serialize messages! Use one of the WriteTo() methods instead! //logger.Log("\n", msgString); System.Environment.Exit(ExitCodes.ExitSend); } string txt = "Mail Sending Succeeded"; logger.Log(txt); bool retval = FileUtils.CreateWriteCloseFile(okFilePath, txt); try { client.Disconnect(true); } catch (Exception ex) { // Ignore, not a fatal error //bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Send Failed\n", ex.Message); logger.Log("Exception in Disconnect to SMTP Server: ", ex.ToString()); } logger.Log("SMTP Client Disconnected. All done."); } System.Environment.Exit(ExitCodes.ExitOk); }
private async Task <bool> getAuthenticated(ClientSecrets cs) { log.Debug("Authenticating with Google calendar service..."); FileDataStore tokenStore = new FileDataStore(Program.UserFilePath); tokenFullPath = Path.Combine(tokenStore.FolderPath, TokenFile); log.Debug("Google credential file location: " + tokenFullPath); if (!tokenFileExists) { log.Info("No Google credentials file available - need user authorisation for OGCS to manage their calendar."); } string[] scopes = new[] { "https://www.googleapis.com/auth/calendar", "email" }; UserCredential credential = null; try { //This will open the authorisation process in a browser, if required credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(cs, scopes, "user", CancelTokenSource.Token, tokenStore); if (tokenFileExists) { log.Debug("User has provided authorisation and credential file saved."); } } catch (Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { //OGCSexception.AnalyseTokenResponse(ex); if (ex.Error.Error == "access_denied") { String noAuthGiven = "Sorry, but this application will not work if you don't allow it access to your Google Calendar :("; log.Warn("User did not provide authorisation code. Sync will not be able to work."); OgcsMessageBox.Show(noAuthGiven, "Authorisation not given", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); throw new ApplicationException(noAuthGiven); } else { Forms.Main.Instance.Console.UpdateWithError("Unable to authenticate with Google. The following error occurred:", ex); } } catch (OperationCanceledException) { Forms.Main.Instance.Console.Update("Unable to authenticate with Google. The operation was cancelled.", Console.Markup.warning); } catch (System.Exception ex) { OGCSexception.Analyse(ex); Forms.Main.Instance.Console.UpdateWithError("Unable to authenticate with Google. The following error occurred:", ex); } if (credential.Token.AccessToken != "" && credential.Token.RefreshToken != "") { log.Info("Refresh and Access token successfully retrieved."); log.Debug("Access token expires " + credential.Token.IssuedUtc.AddSeconds(credential.Token.ExpiresInSeconds.Value).ToLocalTime().ToString()); } GoogleOgcs.Calendar.Instance.Service = new CalendarService(new Google.Apis.Services.BaseClientService.Initializer() { HttpClientInitializer = credential }); if (Settings.Instance.Proxy.Type == "Custom") { GoogleOgcs.Calendar.Instance.Service.HttpClient.DefaultRequestHeaders.Add("user-agent", Settings.Instance.Proxy.BrowserUserAgent); } if (credential.Token.IssuedUtc.AddSeconds(credential.Token.ExpiresInSeconds.Value) < DateTime.UtcNow.AddMinutes(-1)) { log.Debug("Access token needs refreshing."); //This will happen automatically when using the calendar service //But we need a valid token before we call getGaccountEmail() which doesn't use the service int backoff = 0; while (backoff < Calendar.BackoffLimit) { try { GoogleOgcs.Calendar.Instance.Service.Settings.Get("useKeyboardShortcuts").Execute(); break; } catch (Google.GoogleApiException ex) { switch (Calendar.HandleAPIlimits(ref ex, null)) { case Calendar.ApiException.throwException: throw; case Calendar.ApiException.freeAPIexhausted: OGCSexception.LogAsFail(ref ex); OGCSexception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(Calendar.Instance.SubscriptionInvite, ex); OGCSexception.LogAsFail(ref aex); authenticated = false; return(authenticated); case Calendar.ApiException.backoffThenRetry: backoff++; if (backoff == Calendar.BackoffLimit) { log.Fail("API limit backoff was not successful. Retrieving useKeyboardShortcuts setting failed."); authenticated = false; return(authenticated); } else { log.Warn("API rate limit reached. Backing off " + backoff + "sec before retry."); System.Threading.Thread.Sleep(backoff * 1000); } break; } } catch (System.Exception ex) { if (ex is Google.Apis.Auth.OAuth2.Responses.TokenResponseException) { OGCSexception.AnalyseTokenResponse(ex as Google.Apis.Auth.OAuth2.Responses.TokenResponseException, false); } else { OGCSexception.Analyse(ex); Forms.Main.Instance.Console.Update("Unable to communicate with Google services. " + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), Console.Markup.warning); } authenticated = false; return(authenticated); } } log.Debug("Access token refreshed."); } getGaccountEmail(credential.Token.AccessToken); authenticated = true; Forms.Main.Instance.Console.Update("Handshake successful.", verbose: true); return(authenticated); }
/// <summary> /// Initializes a new instance of the <see cref="PlatformRefreshTokenCredential" /> class that uses the supplied /// refresh token to authenticate with Improbable's OAuth servers. /// </summary> /// <param name="refreshToken">The SpatialOS refresh token.</param> /// <param name="tokenServerUrl">The URL of the OAuth token server. Defaults to Improbable's production OAuth token server.</param> /// <param name="scopes">The scope to request for the OAuth server. Defaults to "[*]:*".</param> /// <param name="authServerUrl">The URL of the OAuth auth server. Defaults to Improbable's production OAuth auth server.</param> /// <param name="clientSecrets">The client secrets for the SpatialOS refresh token.</param> public PlatformRefreshTokenCredential(string refreshToken, string authServerUrl = null, string tokenServerUrl = null, IEnumerable <string> scopes = null, ClientSecrets clientSecrets = null) : base( new AuthorizationCodeFlow( new AuthorizationCodeFlow.Initializer( authServerUrl ?? AuthorizationServerUrl, tokenServerUrl ?? TokenServerUrl ) { Scopes = scopes ?? DefaultScopes, ClientSecrets = clientSecrets ?? DefaultSecrets }), DummyUserId, new TokenResponse { RefreshToken = refreshToken } ) { }
private async Task getAuthenticated(ClientSecrets cs) { log.Debug("Authenticating with Google calendar service..."); FileDataStore tokenStore = new FileDataStore(Program.UserFilePath); tokenFullPath = Path.Combine(tokenStore.FolderPath, TokenFile); log.Debug("Google credential file location: " + tokenFullPath); if (!tokenFileExists) { log.Info("No Google credentials file available - need user authorisation for OGCS to manage their calendar."); } string[] scopes = new[] { "https://www.googleapis.com/auth/calendar", "email" }; UserCredential credential = null; try { //This will open the authorisation process in a browser, if required credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(cs, scopes, "user", CancelTokenSource.Token, tokenStore); if (tokenFileExists) { log.Debug("User has provided authorisation and credential file saved."); } } catch (Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { //OGCSexception.AnalyseTokenResponse(ex); if (ex.Error.Error == "access_denied") { String noAuthGiven = "Sorry, but this application will not work if you don't allow it access to your Google Calendar :("; log.Warn("User did not provide authorisation code. Sync will not be able to work."); MessageBox.Show(noAuthGiven, "Authorisation not given", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); throw new ApplicationException(noAuthGiven); } else { Forms.Main.Instance.Console.UpdateWithError("Unable to authenticate with Google. The following error occurred:", ex); } } catch (OperationCanceledException) { Forms.Main.Instance.Console.Update("Unable to authenticate with Google. The operation was cancelled.", Console.Markup.warning); } catch (System.Exception ex) { OGCSexception.Analyse(ex); Forms.Main.Instance.Console.UpdateWithError("Unable to authenticate with Google. The following error occurred:", ex); } if (credential.Token.AccessToken != "" && credential.Token.RefreshToken != "") { log.Info("Refresh and Access token successfully retrieved."); log.Debug("Access token expires " + credential.Token.IssuedUtc.AddSeconds(credential.Token.ExpiresInSeconds.Value).ToLocalTime().ToString()); } GoogleOgcs.Calendar.Instance.Service = new CalendarService(new Google.Apis.Services.BaseClientService.Initializer() { HttpClientInitializer = credential }); if (credential.Token.IssuedUtc.AddSeconds(credential.Token.ExpiresInSeconds.Value) < DateTime.UtcNow.AddMinutes(-1)) { log.Debug("Access token needs refreshing."); //This will happen automatically when using the calendar service //But we need a valid token before we call getGaccountEmail() which doesn't use the service try { GoogleOgcs.Calendar.Instance.Service.Settings.Get("useKeyboardShortcuts").Execute(); } catch (System.Exception ex) { if (ex is Google.Apis.Auth.OAuth2.Responses.TokenResponseException) { OGCSexception.AnalyseTokenResponse(ex as Google.Apis.Auth.OAuth2.Responses.TokenResponseException, false); } else { OGCSexception.Analyse(ex); Forms.Main.Instance.Console.Update("Unable to communicate with Google services.", Console.Markup.warning); } authenticated = false; return; } log.Debug("Access token refreshed."); } getGaccountEmail(credential.Token.AccessToken); authenticated = true; Forms.Main.Instance.Console.Update("Handshake successful.", verbose: true); }
/// <summary> /// The main entry point for the application. /// </summary> public static void Main(string[] args) { Console.WriteLine("This application generates an OAuth2 refresh token for use with " + "the Google Ads API .NET client library. To use this application\n" + "1) Follow the instructions on " + "https://developers.google.com/adwords/api/docs/guides/authentication#create_a_client_id_and_client_secret " + "to generate a new client ID and secret.\n" + "2) Enter the client ID and client Secret " + "when prompted.\n" + "3) Once the output is generated, copy its contents into your App.config file.\n\n"); // Accept the client ID from user. Console.Write("Enter the client ID: "); string clientId = Console.ReadLine(); // Accept the client ID from user. Console.Write("Enter the client secret: "); string clientSecret = Console.ReadLine(); // Load the JSON secrets. ClientSecrets secrets = new ClientSecrets() { ClientId = clientId, ClientSecret = clientSecret }; try { // Authorize the user using installed application flow. Task <UserCredential> task = GoogleWebAuthorizationBroker.AuthorizeAsync( secrets, new string[] { GOOGLE_ADS_API_SCOPE }, String.Empty, CancellationToken.None, new NullDataStore() ); UserCredential credential = task.Result; Console.WriteLine("\nCopy the following content into your App.config file.\n\n" + $"<add key = 'OAuth2Mode' value = 'APPLICATION' />\n" + $"<add key = 'OAuth2ClientId' value = '{clientId}' />\n" + $"<add key = 'OAuth2ClientSecret' value = '{clientSecret}' />\n" + $"<add key = 'OAuth2RefreshToken' value = " + $"'{credential.Token.RefreshToken}' />\n"); Console.WriteLine("/n" + "<!-- Required for manager accounts only: Specify the login customer -->\n" + "<!-- ID used to authenticate API calls. This will be the customer ID -->\n" + "<!-- of the authenticated manager account. It should be set without -->\n" + "<!-- dashes, for example: 1234567890 instead of 123-456-7890. You can -->\n" + "<!-- also specify this later in code if your application uses -->\n" + "<!-- multiple manager account OAuth pairs. -->\n" + "<add key = 'LoginCustomerId' value = INSERT_LOGIN_CUSTOMER_ID_HERE />/n/n"); Console.WriteLine("Press <Enter> to continue..."); Console.ReadLine(); } catch (AggregateException) { Console.WriteLine("An error occured while authorizing the user."); } }
/// <summary>Constructs a new flow using the initializer's properties.</summary> public AuthorizationCodeFlow(Initializer initializer) { clientSecrets = initializer.ClientSecrets; if (clientSecrets == null) { if (initializer.ClientSecretsStream == null) { throw new ArgumentException("You MUST set ClientSecret or ClientSecretStream on the initializer"); } using (initializer.ClientSecretsStream) { clientSecrets = GoogleClientSecrets.Load(initializer.ClientSecretsStream).Secrets; } } else if (initializer.ClientSecretsStream != null) { throw new ArgumentException( "You CAN'T set both ClientSecrets AND ClientSecretStream on the initializer"); } accessMethod = initializer.AccessMethod.ThrowIfNull("Initializer.AccessMethod"); clock = initializer.Clock.ThrowIfNull("Initializer.Clock"); tokenServerUrl = initializer.TokenServerUrl.ThrowIfNullOrEmpty("Initializer.TokenServerUrl"); authorizationServerUrl = initializer.AuthorizationServerUrl.ThrowIfNullOrEmpty ("Initializer.AuthorizationServerUrl"); dataStore = initializer.DataStore; if (dataStore == null) { Logger.Warning("Datastore is null, as a result the user's credential will not be stored"); } scopes = initializer.Scopes; // Set the HTTP client. var httpArgs = new CreateHttpClientArgs(); // Add exponential back-off initializer if necessary. if (initializer.DefaultExponentialBackOffPolicy != ExponentialBackOffPolicy.None) { httpArgs.Initializers.Add( new ExponentialBackOffInitializer(initializer.DefaultExponentialBackOffPolicy, () => new BackOffHandler(new ExponentialBackOff()))); } httpClient = (initializer.HttpClientFactory ?? new HttpClientFactory()).CreateHttpClient(httpArgs); }
static void Main(string[] args) { UserCredential credential; ClientSecrets cs = new ClientSecrets(); //cs.ClientId = "sdfgsdfgsdfg"; //cs.ClientSecret = "fsghfsgsfgs"; // from google cloud string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( cs, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "QuickStart" }); var watch = System.Diagnostics.Stopwatch.StartNew(); var watch2 = System.Diagnostics.Stopwatch.StartNew(); //string root_folder_id = "1ezjmF31xin3bumvC1arKi4wzlyzuCZyK"; string root_folder_id = "root"; List <byte[]> docs = new List <byte[]>(); List <long> times = new List <long>(); try { for (int i = 0; i < 3; i++) { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; ExcelPackage _package = new ExcelPackage(); ExcelWorksheet oSheet; oSheet = _package.Workbook.Worksheets.Add("Test"); oSheet.Cells[2, 1].Value = "TextTextText" + i.ToString(); oSheet.Cells[2, 1].Style.Font.Bold = true; docs.Add(_package.GetAsByteArray()); _package.Dispose(); } watch2.Stop(); var elapsedMs2 = watch2.ElapsedMilliseconds; Console.WriteLine("time xls = " + elapsedMs2 / 1000 + " sec " + elapsedMs2 % 1000 + "msec"); for (int i = 0; i < 3; i++) { var watchi = System.Diagnostics.Stopwatch.StartNew(); createDirectory(service, i.ToString() + " Folder", "Test Folder", root_folder_id); FilesResource.ListRequest listRequest = service.Files.List(); listRequest.Q = "name = '" + i.ToString() + " Folder' and trashed = false"; listRequest.PageSize = 1000; listRequest.Fields = "nextPageToken, files(id, name)"; // List files. IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute() .Files; //Console.WriteLine("Files:"); string rootf = ""; if (files != null && files.Count > 0) { foreach (var file in files) { //Console.WriteLine("{0} ({1})", file.Name, file.Id); rootf = file.Id; } } else { Console.WriteLine("No files found."); } //Console.Read(); Permission perm = new Permission(); perm.Type = "user"; perm.EmailAddress = "*****@*****.**"; perm.Role = "writer"; try { service.Permissions.Create(perm, rootf).Execute(); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } createFile(service, i.ToString() + " Test File.xlsx", "Test Folder", rootf, docs[i]); watchi.Stop(); times.Add(watchi.ElapsedMilliseconds); } } catch (Exception e) { Console.WriteLine(e.Message); } watch.Stop(); var elapsedMs = watch.ElapsedMilliseconds; Console.WriteLine("time all = " + elapsedMs / 1000 + " sec " + elapsedMs % 1000 + "msec"); Console.WriteLine("time avg per 1 folder = " + times.Average() / 1000 + " sec"); Console.ReadKey(); /*FilesResource.ListRequest listRequest2 = service.Files.List(); * listRequest2.Q = "name contains 'Folder' and trashed = false"; * listRequest2.PageSize = 1000; * listRequest2.Fields = "nextPageToken, files(id, name)"; * * IList<Google.Apis.Drive.v3.Data.File> files2 = listRequest2.Execute() * .Files; * if (files2 != null) * { * Console.WriteLine("Files: " + files2.Count); * foreach (var file in files2) * { * deleteFile(service,file.Id); * } * }*/ }