'OAuth2 with gmail account using MailKit do not work on Azure WebJobs
The code works fine on my local machine, but I get an "Access Denied" running it on Azure WebJobs
const string GMailAccount = "[email protected]";
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
});
var codeReceiver = new LocalServerCodeReceiver();
var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver);
var credential = await authCode.AuthorizeAsync(GMailAccount, System.Threading.CancellationToken.None);
if (credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default)) await credential.RefreshTokenAsync(System.Threading.CancellationToken.None);
var oauth2 = new MailKit.Security.SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken);
using (var mailClient = new ImapClient())
{
await mailClient.ConnectAsync("imap.gmail.com", 993, MailKit.Security.SecureSocketOptions.SslOnConnect);
await mailClient.AuthenticateAsync(oauth2);
var inbox = mailClient.Inbox;
inbox.Open(FolderAccess.ReadWrite);
var items = inbox.Fetch(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.Size | MessageSummaryItems.Flags);
// iterate over all of the messages and fetch them by UID
foreach (var item in items)
{
var uid = item.UniqueId;
var myMessage = inbox.GetMessage(uid);
Console.WriteLine(uid);
}
await mailClient.DisconnectAsync(true);
}
Azure WebJob log :
exception.System.Net.HttpListenerException (5
): Access is denied
at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.AuthorizeAsync(String userId, CancellationToken taskCancellationToken)
Solution 1:[1]
The problem is that you are using the code for desktop apps instead of web apps (see your call to AuthorizationInstalledApp).
That call expects to be able to spawn a desktop browser window which obviously won’t work for a web app running on a headless server.
If you are using ASP.NET, someone just recently sent me a sample to include in MailKit’s GMailOAuth2.md file.
Solution 2:[2]
I'm not sure about your overall algorithm. But you can filter out the None values simply by assigning the result of freq to a variable before printing it. Then you can check if it's not None.
for a in var1_bin:
for key in range(256):
decoded = ''.join(chr(b ^ key) for b in a)
decoded_freq = freq(decoded, ascii_letters)
if decoded_freq:
print(key, decoded_freq)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jstedfast |
| Solution 2 | Barmar |
