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); } }
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); }
/// <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); }
private async Task <UserCredential> AuthorizeAsync(GoogleAuthorizationCodeFlow.Initializer initializer, string user) { var flow = new GoogleAuthorizationCodeFlow(initializer); var codeReceiver = new LocalServerCodeReceiver(); // Create an authorization code installed app instance and authorize the user. return(await new AuthorizationCodeInstalledApp(flow, codeReceiver).AuthorizeAsync (user, CancellationToken.None).ConfigureAwait(false)); }
/// <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); } }
public async Task GetAndValidateJwt() { // Warning: This test is interactive! // It will bring up a browser window that must be responded to before the test can complete. // Do auth. var codeReceiver = new LocalServerCodeReceiver(); var nonce = "nonce_but_randomly_generate_in_real_code"; var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecretsStream = Helper.GetClientSecretStream(), Scopes = new string[] { "openid", "email" }, Nonce = nonce, }; var flow = new GoogleAuthorizationCodeFlow(initializer); var redirectUri = codeReceiver.RedirectUri; AuthorizationCodeRequestUrl codeRequest = flow.CreateAuthorizationCodeRequest(redirectUri); // Receive the code. var response = await codeReceiver.ReceiveCodeAsync(codeRequest, CancellationToken.None); var code = response.Code; // Get a JWT from code. var secretJson = JToken.Parse(Helper.GetClientSecret()); var codeReq = "https://oauth2.googleapis.com/token"; var contentStr = "code=" + code + "&client_id=" + secretJson["installed"]["client_id"] + "&client_secret=" + secretJson["installed"]["client_secret"] + "&redirect_uri=" + redirectUri + "&grant_type=authorization_code"; var contentBytes = Encoding.ASCII.GetBytes(contentStr); var content = new ByteArrayContent(contentBytes); content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); var httpClient = new HttpClient(); var res = httpClient.PostAsync(codeReq, content).Result; var json = JToken.Parse(Encoding.UTF8.GetString(await res.Content.ReadAsByteArrayAsync())); var jwt = (string)json["id_token"]; // Confirm JWT is valid var validPayload = await GoogleJsonWebSignature.ValidateAsync(jwt); Assert.NotNull(validPayload); // Confirm nonce matches Assert.Equal(nonce, validPayload.Nonce); }
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); }
/// <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); } }