Invalid Credential with XOAuth2 for Gmail - google-oauth

Recently, I am trying to get e-mails from Gmail, using XOAuth2 protocol.
Especially, I am using "OAuth2Authenticator.java" from https://code.google.com/p/google-mail-oauth2-tools/downloads/list.
But, I always get an invalid credential error like the follwoing:
A1 NO [ALERT] Invalid credentials (Failure)
Exception in thread "main" javax.mail.AuthenticationFailedException: [ALERT] Invalid credentials (Failure)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:566)
at javax.mail.Service.connect(Service.java:265)
Before reading, due to the limitation of putting a link, I cannot write "httoo://" so that please think of that this http header is front of some url information.
Before posting this question, I think I looked most of the articles about this one. Many articles are about using OAuth1.0 (deprecated) But, I still cannot figure out how I can make it work with OAuth2 & XOAuth2. I appreciate any suggestion/helps.
The following is the steps I am taking:
get an access token through OAuth2 with the scope of mail.google.com/
just put this access token & gmail account (e.g. test#gmail.com) into "OAuth2Authenticator.java".
After this procedure, I always get invalid credential.
The interesting stuff is that I can get unread mails through Feed URL (i.e. https://mail.google.com/mail/feed/atom) which is specified in Google OAuth2.0 Playground.
This indicates that I am sure that I get the correct access token. But, does not work at all for IMAP with this sample code.
Actually, the scope "mail.google.com/" is not included in the list of Google OAuth2.0 Playground.
For getting access token for XOAuth2, is there any other special way to get access token?
For the official page about XOAuth2, we need to use base64 to encode the access token.
But, I think the sample code is doing this procedure.
Also, SMTP of this sample did not work at all. But, after changing the properties, I could make it work. Is this code old?
But, unfortunately, what I need is IMAP. But, after trying setting some different/new properties, IMAP does not work at all....
I am stuck on this problem for a long time. So, I posted this question.
I really appreciate any suggestion/helps.
Regards

I figured out your problem regarding invalid credentials
A1 NO [ALERT] Invalid credentials (Failure) Exception in thread "main"
javax.mail.AuthenticationFailedException: [ALERT] Invalid credentials (Failure) at
com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:566) at
javax.mail.Service.connect(Service.java:265)
To remove above error you have to invalidate your Token and get a new token using below code
1- accountManager.invalidateAuthToken("com.google", token);
after invalidate token you have to get Refresh token using below code
String newToken = AccountManager.get(this).getAuthToken(new Account(account,"com.google"),
AUTH_TOKEN_TYPE, true, null, null).getResult().getString(AccountManager.KEY_AUTHTOKEN);
using new token now you are able to login.

Related

Google API PHP Authentication Invalid Token Format (the question and the answer)

When running the sample code from the Google Calendar API PHP Example Page, it said "Enter verification code:" at which point I put in my 2FA code from Google Authenticatior.
This produced "Fatal error: Uncaught InvalidArgumentException: Invalid token format in /vendor/google/apiclient/src/Google/Client.php:434"
I spent several hours verifying keys and json formats and googling, until I finally discovered that it does not want a 2FA token, it wants a completely different token.
If you copy and paste the link it gives you into a browser, get the token it returns, then copy and paste the token back into the "token" prompt, everything works.
This was 100% my fault, but I'm posting this here in the hopes of saving other people from also wasting time.
If any google employees are reading this, it would be nice to make the "token" prompt and the error message less ambiguous.

Authentication on Instagram to get the access_token using the API

I'm using the Instagram API and want to get the access_token in order to throw api requests over my own account. When I try to follow the first step and get the authorization code programmatically using RestTemplate I can't get it work.
String AUTHORIZE_URL = "https://api.instagram.com/oauth/authorize/?client_id=<CLIENT_ID>&redirect_uri=<REDIRECT_URI>&response_type=code";
String url = String.format(AUTHORIZE_URL, clientId, redirectUri);
String o = restTemplate.getForObject(url, String.class);
The response is the html code of the login page because Instagram requires the user to be logged in to check if the app is authorized (of course it is, since the app an the user belongs to my own account).
How can I authenticate before throwing that request so they return the code to my redirectUri and not complain about login?
Note: I tried simulating the request to their login form but it returned a 403 Forbidden.
NOTE: I already got a valid access_token, manually generated, and it works perfectly but I want to implement also a process to re-generate a new access_token automatically since they may invalidate it at any time in the future.
Even though our access tokens do not specify an expiration time, your app should handle the case that either the user revokes access, or Instagram expires the token after some period of time. If the token is no longer valid, API responses will contain an “error_type=OAuthAccessTokenError”. In this case you will need to re-authenticate the user to obtain a new valid token.
In other words: do not assume your access_token is valid forever.
Instagram is upgrading their APIs and the flows. Earlier we needed access token to bypass forced login screen. Since yesterday, they have removed that.
Now if you call this code, it will check if you are already logged in or not. If so, it will call the AUTHORIZE_URL of yours and will send a response code. The format will be either:
On success validation - http://your-redirect-uri?code=CODE
On error - http://your-redirect-uri?error=access_denied&error_reason=user_denied&error_description=The+user+denied+your+request
Now what I'm doing is I'm directly calling the above URL of yours every time. Now if the user is logged in, a response code will be sent to you, else user will be asked to login and validate your app and then the code will be sent. Technically, you are eliminating the possibility of the error case! So no need of overhead of storing access token in your database or verifying its validity.
Just try and check now what happens.
PS: If you want to check API behavior, simply type the URL on the browser and check what it returns! It helped me a lot while coding and debugging! :)

Facebook Login without JSSDK, how to get token if already authorized previously

So I am updating an older desktop app (written in VB, .net 4.0) with facebook integration and followed the guide found here, and have been able to successfully get a token (by parsing the uri of the embedded webview if it contains "token="). Now my problem is if I try to login with a facebook account that has already approved the app in a prior session, the webview just gets redirected to https://www.facebook.com/connect/login_success.html without any token information.
Do I HAVE to log all of the tokens I generate manually (ie on successful token generation, I can call their profile info, use their FB ID as key and save the token)? Even if I do, since the email and password is input directly into the facebook login window, how do I check if the user already has a token?
Thanks in advance
The access token can change any time, you need to get it everytime. After getting the token, I immediately get the user information https://graph.facebook.com/me?access_token=??? and use that ID to find their database information.
I couldn't quickly find facebook information but on google's oauth information it says "The access token is also associated with a limited scope that define the kind of data the your client application has access to (for example "Manage your tasks"). An important goal for OAuth 2.0 is to provide secure and convenient access to the protected data, while minimizing the potential impact if an access token is stolen."
https://code.google.com/p/google-api-php-client/wiki/OAuth2
Ok so I finally figured it out myself. My mistake was apparently requesting the access_token directly (ie https://www.facebook.com/dialog/oauth?response_type=token...) to try and save time.
I fixed it by making a request for a 'code' instead (ie https://www.facebook.com/dialog/oauth?response_type=code), which I then use to make a second request to retrieve an access token as documented here: https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/, "Exchanging code for an access token" section a bit lower on the page.
Hope this helps someone in the future, this was very frustrating on my part.
Regards,
Prince

API Authorization token error

I'm trying to use the Survey API.
When I try and use the form online to request an Authorization token I get a
error message.
Invalid or missing access token" error message.
The form to test the API calls also asks for a Client Secret code but yet it auto fills the box with the API Key.
Any help here would be nice.
I'm not sure if this is a bug on Survey Monkey's end either in the API or the form that tests the API.
You should have received a reply to this via email but I wanted to ensure this was answered here in case anyone else is having the same issue.
There was a bug on our API console preventing an access token being issued, this is now fixed.
The access token has to be copied into the "Authorization" parameter in the format "bearer ". e.g. if your access token is 'fdhjfu3cc8ss=', make sure the Authorization parameter has "bearer fdhjfu3cc8ss=" in it (with no quotes). Note that you need to use the Access Token returned, not the Authorization Code.

Error Validating Access Token

I get this error occasionally:
Fatal error: Uncaught Exception: 190: Error validating access token: This may be because the user logged out or may be due to a system error. thrown in ..base_facebook.php on line 1053
The issue is that I get it at random times, without any warning. I can go weeks without seeing it, then all of a sudden it will come up. The solution? You can wait it out. It throws this error for about 15 minutes then you can refresh and it will allow you to continue with what you were doing.
My question is, is this an issue on my end? Or is this a Facebook issue? This is a Facebook connect page if that helps. I did research and found out it could be caused from the FQL query. But then wouldn't it be consistent at least? It seems like it is completely random. Here is my FQL query anyway just in case.
$facebook->api(array('method' => 'fql.query','query' => "SELECT first_name,middle_name,last_name,email,affiliations FROM user WHERE uid=".$user));
Here are lines 1052-1071 of Base_Facebook,
protected function throwAPIException($result) {
$e = new FacebookApiException($result);
switch ($e->getType()) {
// OAuth 2.0 Draft 00 style
case 'OAuthException':
// OAuth 2.0 Draft 10 style
case 'invalid_token':
// REST server errors are just Exceptions
case 'Exception':
$message = $e->getMessage();
if ((strpos($message, 'Error validating access token') !== false) ||
(strpos($message, 'Invalid OAuth access token') !== false)) {
$this->setAccessToken(null);
$this->user = 0;
$this->clearAllPersistentData();
}
}
throw $e;
}
Thank you
As written in How-To: Handle expired access tokens (link is broken) developers blog post
Access tokens for users can become invalid due to various reasons. In most cases, they can expire if it’s past the time specified by the expires field (by default access token have a 2 hour lifetime). What many developers do not realize is that an access token can also expire if a user changes her password, logs out or if she de-authorizes the app via the App Dashboard. It is very important that your apps handle such situations. If your access token expires, you need to reacquire a valid access token.
Before we could use offline_access permission to get token that not expire (unless user is connected with application), this permission is now deprecated, see Deprecation of Offline Access Permission to see how you can get access_token with longer expiration time.
Update:
As of Aug 2012 Facebook PHP-SDK have added simple way of extending access_token (see How to extend access token validity since offline_access deprecation for more details)
Update 2:
Note that original blog-post from Facebook about expired tokens handling doesn't exists anymore. There is new documentation hewever that may be used to get the details.
https://developers.facebook.com/docs/facebook-login/access-tokens/#extending