I've trying to use Mailkit and OAuth to read a user's Gmail inbox, and have followed the sample code found in the Mailkit FAQ. For the record, here is the code I'm using...
Note that I'm currently storing the token in a file in the site's content root, just until I get this working. After that, I'll be implementing an Entity Framework IDataStore, so please don't be concerned about the security issue of the code shown here
private async Task<ImapClient> GetMailClientOAuth(string account, string clientId, string clientSecret) {
ClientSecrets clientSecrets = new() {
ClientId = clientId,
ClientSecret = clientSecret
};
GoogleAuthorizationCodeFlow codeFlow = new(new GoogleAuthorizationCodeFlow.Initializer {
DataStore = new FileDataStore($@"{_env.ContentRootPath}\{account}"),
Scopes = new[] { "https://mail.google.com/" },
ClientSecrets = clientSecrets
});
LocalServerCodeReceiver codeReceiver = new();
AuthorizationCodeInstalledApp authCode = new(codeFlow, codeReceiver);
UserCredential credential = await authCode.AuthorizeAsync(account, CancellationToken.None);
if (authCode.ShouldRequestAuthorizationCode(credential.Token)) {
await credential.RefreshTokenAsync(CancellationToken.None);
}
SaslMechanismOAuth2 oauth2 = new(credential.UserId, credential.Token.AccessToken);
ImapClient client = new();
await client.ConnectAsync("imap.gmail.com", 993, SecureSocketOptions.SslOnConnect);
await client.AuthenticateAsync(oauth2);
return client;
}
The code worked fine in a test console app, and I'm now trying to integrate the code into my ASP.NET Core web app.
I set up a web project in my Google Cloud dashboard, added the Gmail API and created an OAuth credential, just like I did for the console app.
When I try the code that access Gmail, I get a window pop up in my browser with a message...
Authorization Error
Error 400: redirect_uri_mismatch
The redirect URI in the request, http://localhost:54392/authorize/, does not match the ones authorized for the OAuth client
Now I have no idea where it picked up http://localhost:54392/authorize/, as it doesn't bear any resemblance to anything I'm using (not that I gave it any URL anyway), but I followed the link that was in the message, and set a URL that is on my web site (when running on my local machine).
I have double-checked that this URL has been saved with the credential, but when I try and access the page on my site, I get the same error, with the same URL it thinks should be there.
I have checked the client ID and secret, and I'm definitely using the right ones.
Anyone any idea where it's getting http://localhost:54392/authorize/ from, and how I tell it to use something else?
Thanks