问题
I'm trying to use XOAUTH2 to authenticate IMAP calls to Gmail (yes I'm aware there is a Gmail API but I have my reasons to stick to IMAP).
I get a valid token by either using:
GoogleAuthUtil.getToken(Context context, String account, "oauth2:" + GmailScopes.MAIL_GOOGLE_COM)
or
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
context, Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff())
.setSelectedAccountName(account);
credential.getToken();
They both return the same token so either way seems to work. The returned tokens are valid according to this:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=xyz
Returns:
{
"issued_to": "myclientid....apps.googleusercontent.com",
"audience": "myclientid....apps.googleusercontent.com",
"scope": "https://mail.google.com https://mail.google.com/",
"expires_in": 619,
"access_type": "online"
}
Nevertheless if I do call AUTHENTICATE in my imap session like so:
AUTHENTICATE XOAUTH2 dXNlcj1zb21ldXNlckBleGFtcGxlLmNvbQFhdXRoPUJlYXJlciB2RjlkZnQ0cW1UYzJOdmIzUmxja0JoZEhSaGRtbHpkR0V1WTI5dENnPT0BAQo=
with the base64 encoded part being:
user=emanuel.moecklin@gmail.com^Aauth=Bearer ya29.AwKAJ0L6Wm06wxMd4rhIl0YHrsnnWyIJ9XPSlCRhhx2XffuP5F8ibptTOMjGP8WELkUCYQ^A^A
(^A stands for Control A as in 0x1)
I still get the response: {"status":"400","schemes":"Bearer","scope":"https://mail.google.com/"}
which seems to indicate that "something" is wrong with the token (expired, missing scope or whatnot).
I used the correct scope, the client id of the token matches my apps' client id in the Google developer console, the fingerprint has the correct value and the package name matches my apps' package name so what am I doing wrong?
回答1:
Nevermind it was a beginner's mistake. The IMAP command parameter was built like this:
String para = "user=" + myuser + 0x1 + "auth=Bearer " + token + 0x1 + 0x1;
Unfortunately 0x1 doesn't translate into ^A (ascii code 1) but into 1 (number 1).
What I need to do is:
String para = "user=" + myuser + (char)0x1 + "auth=Bearer " + token + (char)0x1 + (char)0x1;
I leave the question since it contains some good information on how to implement XOAUTH2 with IMAP and everyone who has implemented XOAUTH2 knows how confusing that can be (considering how much/little/outdated/contradicting documentation one can find one the topic).
来源:https://stackoverflow.com/questions/32954851/gmail-xoauth-2-0-imap-authenticate-returns-status400