private async Task ConfigurarOAuth2Async() { var clientSecrets = new ClientSecrets { ClientId = _configuration["MsjConfiguration:Gmail:ClientId"], ClientSecret = _configuration["MsjConfiguration:Gmail:ClientSecret"] }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore(_configuration["MsjConfiguration:Gmail:CredentialLocation"], true), Scopes = new[] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(_configuration["MsjConfiguration:Gmail:UserId"], CancellationToken.None); if (credential.Token.IsExpired(SystemClock.Default)) { await credential.RefreshTokenAsync(CancellationToken.None); } oAuth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); }
public async Task <SaslMechanismOAuth2> Token() { var clientSecrets = new ClientSecrets { ClientId = Id, ClientSecret = Secret }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore("CredentialCacheFolder", false), Scopes = new[] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(Mail, CancellationToken.None); //if (authCode.ShouldRequestAuthorizationCode(credential.Token)) // await credential.RefreshTokenAsync(CancellationToken.None); // Refresh Token if needed (1h timeout) if (credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default)) { await credential.RefreshTokenAsync(CancellationToken.None); } var oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); return(oauth2); }
// Connexion OAuth2 vers une messagerie gmail private async void connexionGmail() { var clientSecrets = new ClientSecrets { ClientId = "294403304718-bptp75nbk64qi2klfvjidqvklmcqp9vm.apps.googleusercontent.com", ClientSecret = "0PuD1zj5uq62HvWZx1t9RrKc" }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore("CredentialCacheFolder", false), Scopes = new[] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(I_Connexion_Login.Text, CancellationToken.None); if (authCode.ShouldRequestAuthorizationCode(credential.Token)) { await credential.RefreshTokenAsync(CancellationToken.None); } var oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); using (var client = new ImapClient()) { await client.ConnectAsync("imap.gmail.com", 993, SecureSocketOptions.SslOnConnect); // non paramètrable await client.AuthenticateAsync(oauth2); await client.DisconnectAsync(true); } }
/// <summary> /// Get OAUTH2 token needed to Authenticate SMTP client /// </summary> /// <PARAM name="userAccount"></PARAM> /// <PARAM name="clientSecrets"></PARAM> /// <PARAM name="accessScopes"></PARAM> /// <returns></returns> public static SaslMechanism GetAuth2Token(string userAccount, ClientSecrets clientSecrets, string[] accessScopes) { var AppFileDataStore = new FileDataStore("CredentialCacheFolder", false); var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = AppFileDataStore, Scopes = accessScopes, ClientSecrets = clientSecrets }); var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( clientSecrets , accessScopes , userAccount , CancellationToken.None , AppFileDataStore).Result; if (credential.Token.IsExpired(SystemClock.Default)) { credential.RefreshTokenAsync(CancellationToken.None); } // Note: We use credential.UserId here instead of GMail account because the user *may* have chosen a // different GMail account when presented with the browser window during the authentication process. SaslMechanism oauth2; oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); return(oauth2); }
/// <summary> /// Get Access Token from Google OAuth 2.0 API /// </summary> /// <returns>The UserCredentials with Access Token and Refresh Token</returns> private async Task <UserCredential> GetAuthorization() { if (!LoadConfiguration()) { return(null); } // Set up the Installed App OAuth 2.0 Flow for Google APIs with a custom code receiver that uses the Browser inside a native Form. GoogleAuthorizationCodeFlow.Initializer myInitializer = new GoogleAuthorizationCodeFlow.Initializer(); myInitializer.ClientSecrets = new ClientSecrets() { ClientId = m_clientId, ClientSecret = m_clientSecret.ReadString() }; myInitializer.Scopes = new[] { DriveService.Scope.Drive }; GoogleAuthorizationCodeFlow myFlow = new GoogleAuthorizationCodeFlow(myInitializer); //myFlow.HttpClient.Timeout = new TimeSpan(0, 0, 10); // 10s NativeCodeReceiver myCodeReceiver = new NativeCodeReceiver(m_entry.Strings.Get(PwDefs.UserNameField).ReadString(), m_entry.Strings.Get(PwDefs.PasswordField)); AuthorizationCodeInstalledApp myAuth = new AuthorizationCodeInstalledApp(myFlow, myCodeReceiver); UserCredential myCredential = null; // Try using an existing Refresh Token to get a new Access Token if (m_refreshToken != null && !m_refreshToken.IsEmpty) { try { TokenResponse myTokenResponse = await myAuth.Flow.RefreshTokenAsync("user", m_refreshToken.ReadString(), CancellationToken.None); myCredential = new UserCredential(myFlow, "user", myTokenResponse); } catch (TokenResponseException ex) { switch (ex.Error.Error) { case "invalid_grant": myCredential = null; // Refresh Token is invalid. Get user authorization below. break; default: throw ex; } } } // Let the User authorize the access if (myCredential == null || String.IsNullOrEmpty(myCredential.Token.AccessToken)) { myCredential = await myAuth.AuthorizeAsync("user", CancellationToken.None); // save the refresh token if new or different if (myCredential != null && !String.IsNullOrEmpty(myCredential.Token.RefreshToken) && (m_refreshToken == null || myCredential.Token.RefreshToken != m_refreshToken.ReadString())) { m_refreshToken = new ProtectedString(true, myCredential.Token.RefreshToken); SaveConfiguration(); } } return(myCredential); }
/// <summary> /// Odeslání emailu přes GMail /// </summary> /// <param name="email">emailová adresa příjemce</param> /// <param name="subject">předmět mailu</param> /// <param name="text">plain textová podoba obsahu</param> /// <returns>nic</returns> public async Task SendEmailAsync(string email, string subject, string text) { var message = new MimeMessage(); // vytvoření mailové zprávy message.From.Add(new MailboxAddress(_configuration["GmailSender:FromName"], _configuration["GmailSender:From"])); message.To.Add(new MailboxAddress(email, email)); message.Subject = subject; var bodyBuilder = new BodyBuilder(); bodyBuilder.TextBody = text; bodyBuilder.HtmlBody = text; message.Body = bodyBuilder.ToMessageBody(); // GMail OAUTH Flow var clientSecrets = new ClientSecrets { ClientId = _configuration["GmailSender:AppID"], ClientSecret = _configuration["GmailSender:AppSecret"] }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore("CredentialCacheFolder", false), Scopes = new[] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(_configuration["GmailSender:AccountID"], CancellationToken.None); if (credential.Token.IsExpired(SystemClock.Default)) { await credential.RefreshTokenAsync(CancellationToken.None); } var oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); if (Int32.TryParse(_configuration["GmailSender:Port"], out int port) == false) { port = 0; // v konfiguraci je port uveden jako text, potřebujeme ho jako číslo } using (var client = new SmtpClient()) // vytvoření SMTP klienta { await client.ConnectAsync(_configuration["GmailSender:Server"], port, SecureSocketOptions.StartTlsWhenAvailable); await client.AuthenticateAsync(oauth2); await client.SendAsync(message); await client.DisconnectAsync(true); } }
/// Request Oauth2 credentials through Google. public OAuth2CredentialRequest(ClientSecrets secrets, IEnumerable <string> scopes, string callbackPath, IDataStore dataStore) { // Use Google authorization code flow, which has hardcoded authorization server and token server // URLs. IsGoogle = true; var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = scopes, DataStore = dataStore, }; var authFlow = new GoogleAuthorizationCodeFlow(initializer); var codeReceiver = new LocalHttpCodeReceiver(callbackPath); m_AppFlow = new AuthorizationCodeInstalledApp(authFlow, codeReceiver); }
public GoogleAuthAdapter( GoogleAuthorizationCodeFlow.Initializer initializer, string closePageReponse) { // Add email scope. this.initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = initializer.ClientSecrets, Scopes = initializer.Scopes.Concat(new[] { GoogleAuthAdapter.EmailScope }), DataStore = initializer.DataStore }; this.flow = new GoogleAuthorizationCodeFlow(this.initializer); this.installedApp = new AuthorizationCodeInstalledApp( this.flow, new LocalServerCodeReceiver(closePageReponse)); }
private async Task <IYouTubeServiceWrapper> CreateYouTubeService(bool getNewToken) { if (_youTubeServiceWrapper != null && !getNewToken) { return(_youTubeServiceWrapper); } //var entropy = _entropyService.GetEntropy(); //var decryptedApiKey = _dpapiService.Decrypt(_appSettings.ApiKey); // TODO: if requesting new scopes, delete %appdata%\_youTubeServiceCreatorOptions.FileDataStoreName\.* - this is where the refresh/accesstoken/scopes are stored UserCredential credential; using (var stream = new FileStream(_youTubeServiceCreatorOptions.ClientSecretPath, FileMode.Open, FileAccess.Read)) { var installedApp = new AuthorizationCodeInstalledApp( new GoogleAuthorizationCodeFlow( new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = GoogleClientSecrets.Load(stream).Secrets, // Console app should only need ReadOnly. the UI needs write access Scopes = new List <string> { YouTubeService.Scope.YoutubeReadonly, YouTubeService.Scope.Youtube }, DataStore = new FileDataStore(_youTubeServiceCreatorOptions.FileDataStoreName) }), new LocalServerCodeReceiver()); credential = await installedApp.AuthorizeAsync("user", CancellationToken.None); } if (getNewToken) { await credential.RefreshTokenAsync(CancellationToken.None); } // Create the service. _youTubeServiceWrapper = new YouTubeServiceWrapper(new BaseClientService.Initializer() { ApiKey = _appSettings.ApiKey, HttpClientInitializer = credential, ApplicationName = "YouTube cleanup tool", }); return(_youTubeServiceWrapper); }
private static UserCredential CreateCredentials() { var encoded = Environment.GetEnvironmentVariable("GOOGLE_CLIENT_SECRETS"); var decoded = Base64Decode(encoded); var stream = new MemoryStream(Encoding.UTF8.GetBytes(decoded)); var flow = new GoogleAuthorizationCodeFlow( new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = GoogleClientSecrets.Load(stream).Secrets, Scopes = Scopes, DataStore = new EnvironmentDataStore("GOOGLE_AUTH_TOKEN") }); var credential = new AuthorizationCodeInstalledApp( flow, new PromptCodeReceiver()).AuthorizeAsync("user", CancellationToken.None).Result; return(credential); }
private static async Task <UserCredential> LoginToGoogle(string user, IWebProxy proxyOrNull) { GoogleAuthorizationCodeFlow.Initializer initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = CreateClientSecrets(), HttpClientFactory = new ProxySupportedHttpClientFactory(proxyOrNull), Scopes = new[] { "https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/carddav", "https://www.googleapis.com/auth/tasks", "https://www.google.com/m8/feeds/" // => contacts }, DataStore = new FileDataStore(GoogleWebAuthorizationBroker.Folder) }; var authorizer = new AuthorizationCodeInstalledApp( new AuthorizationCodeFlowWithLoginHint(initializer, user), new LocalServerCodeReceiver()); return(await authorizer.AuthorizeAsync(user, CancellationToken.None)); }
static async Task OAuthAsync(ImapClient client) { var clientSecrets = new ClientSecrets { ClientId = "XXX.apps.googleusercontent.com", ClientSecret = "XXX" }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore("CredentialCacheFolder", false), Scopes = new [] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); // Note: For a web app, you'll want to use AuthorizationCodeWebApp instead. var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(GMailAccount, CancellationToken.None); if (credential.Token.IsExpired(SystemClock.Default)) { await credential.RefreshTokenAsync(CancellationToken.None); } // Note: We use credential.UserId here instead of GMailAccount because the user *may* have chosen a // different GMail account when presented with the browser window during the authentication process. SaslMechanism oauth2; if (client.AuthenticationMechanisms.Contains("OAUTHBEARER")) { oauth2 = new SaslMechanismOAuthBearer(credential.UserId, credential.Token.AccessToken); } else { oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); } await client.AuthenticateAsync(oauth2); }
/// Request Oauth2 credentials through a third party by providing authorization and token server /// URLs. public OAuth2CredentialRequest(ClientSecrets secrets, IEnumerable <string> scopes, string callbackPath, IDataStore dataStore, string authorizationServerUrl, string tokenServerUrl) { Debug.Assert(!string.IsNullOrWhiteSpace(authorizationServerUrl), "Missing authorization server url"); Debug.Assert(!string.IsNullOrWhiteSpace(tokenServerUrl), "Missing token server url"); // Use the generic authorization code flow with the provided authorization and token // server urls. IsGoogle = false; var initializer = new AuthorizationCodeFlow.Initializer(authorizationServerUrl, tokenServerUrl) { ClientSecrets = secrets, Scopes = scopes, DataStore = dataStore, }; var authFlow = new AuthorizationCodeFlow(initializer); var codeReceiver = new LocalHttpCodeReceiver(callbackPath); m_AppFlow = new AuthorizationCodeInstalledApp(authFlow, codeReceiver); }
/// <summary> /// Utilizes MailKit and Google APIs to send an email /// </summary> /// <param name="person">User's Email</param> /// <returns></returns> private async Task EmailContestantAsync(Person person, string email, Event details) { const string GMailAccount = "*****@*****.**"; var clientSecrets = new ClientSecrets { ClientId = Services.AuthKeys.Google_OAuth, ClientSecret = Services.AuthKeys.Google_Client, }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore("CredentialCacheFolder", false), Scopes = new[] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); // Note: For a web app, you'll want to use AuthorizationCodeWebApp instead. var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(GMailAccount, CancellationToken.None); if (credential.Token.IsExpired(SystemClock.Default)) { await credential.RefreshTokenAsync(CancellationToken.None); } var oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); var message = new MimeMessage(); message.From.Add(new MailboxAddress("Happnin", "*****@*****.**")); message.To.Add(new MailboxAddress($"{person.FullName}", email)); message.Subject = "Please Confirm"; message.Body = new TextPart("plain") { Text = $"Hello {person.FirstName} \n" + $"You have signed up for \n" + $"{details.EventName}\n" + $"on {details.EventDate} \n" + $"\n" + $"Enjoy!\n" + $"Happnin'\n" //somekind of confirm button here }; using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 587); // use the OAuth2.0 access token obtained above client.Authenticate(oauth2); client.Send(message); client.Disconnect(true); } }