mstefanik
mstefanik

Reputation: 61

Gmail authentication failure for IMAP but not POP3

I've gone through the process of creating an OAuth2 access token for a test application on my Google account (not using GSuite) and whenever I try to use it to authenticate using XOAUTH2 with imap.google.com, it fails and returns {"status":"400","schemes":"Bearer","scope":"https://mail.google.com/"} followed by the IMAP status response NO [AUTHENTICATIONFAILED] Invalid credentials (Failure)

I've seen some other similar issues raised, and it turns out the problem was because they didn't use the scope https://mail.google.com/ when requesting the token. However, I did use that scope and the token validates; using https://www.googleapis.com/oauth2/v1/tokeninfo it returns:

{
  "issued_to": "xxxxx.apps.googleusercontent.com",
  "audience": "xxxxx.apps.googleusercontent.com",
  "scope": "https://mail.google.com/",
  "expires_in": 2083,
  "access_type": "offline"
}

The thing is, the same token works just fine with authenticating using Google's POP3 server, connecting to pop.gmail.com. It seems to be an issue specific to IMAP, and I checked, both POP3 and IMAP access are enabled for the Gmail account I'm testing with.

In addition, the same IMAP code which performs the XOAUTH2 authentication works just fine with Outlook and their access token. So I'm at a loss as to why Google is rejecting a valid token when I'm using the broadest scope available.

Any suggestions or insights would be welcome.

Upvotes: 1

Views: 1265

Answers (1)

mstefanik
mstefanik

Reputation: 61

After doing some more testing, I was able to get this to work. The solution won't likely be helpful for anyone who isn't rolling their own OAuth2 code, but here was the problem. I was encoding the AUTHENTICATE request like this (where ^A is the SOH control character):

^[email protected]^Aauth=bearer ya29.a0AfH6SMA8fcO_RkV3sH73f.....^A^A

Google's POP3 server was completely fine with this, and so was Outlook's mail servers. However, Google's IMAP server apparently had a real issue with "bearer" not being capitalized. After reviewing RFC 7628, and despite this explicitly in the standard:

Note to implementers: The SASL OAuth method names are case insensitive. One example uses "Bearer" but that could as easily be "bearer", "BEARER", or "BeArEr".

Changing the request to use "auth=Bearer" instead of "auth=bearer" allowed the client to authenticate. This is clearly a Google issue, but at least it's resolved.

Upvotes: 1

Related Questions