I'm using the google-api-client gem in my Rails project. I have omniauth and devise working, and I have users authenticate through Google.
I thought I had this going very well, until recently. I've noticed my app will throw an error when it fetches the Google Calendar API after one hour. The expiration is one hour from authentication time, and from then I get this error:
Signet::AuthorizationError (Authorization failed. Server message:
{
"error" : "invalid_grant",
"error_description" : "Token has been revoked."
}):
This is separate from invalid refresh tokens, as I do have the refresh token stored in the database. It is sending the refresh token request, which spurs that error above, with this code:
client = Google::APIClient.new(
:application_name => APP_NAME,
:application_version => APP_VERSION,
)
client.authorization.client_id = CLIENT_ID
client.authorization.client_secret = CLIENT_SECRET
client.authorization.refresh_token = user.auth_refresh_token
token_result = client.authorization.fetch_access_token!
I have been very careful as to not sign in and out of my Google accounts, so I cannot figure out why Google would send back this message. If I refresh the page after 55 minutes, all is okay. If I refresh the page after 1 hour, it complains about the access token being revoked.
Has anyone had this issue before? If so, what did you do to fix it? Was it something you had to change in Google's Developer Console?
I ended up figuring out the issue, so I thought I'd share what fixed it.
In config/initializers/devise.rb, I have:
scope: 'userinfo.profile, userinfo.email, calendar, https://www.googleapis.com/auth/gmail.readonly', prompt: 'select_account consent' }
What did it for me was the prompt: 'select_account consent' part. Asking the user for consent at each login seems to keep the refresh token up to date. When the user logs in via Google I check if there was a refresh token in the response, and if there was I save that to the database. If not, I keep their current refresh token in the database.
In all honesty, I really don't get why it was necessary for me to do this but for other users who've shared their code examples it was fine. Perhaps there was a change in the Google's OAuth2 or maybe there's a discrepancy in my method of handling the authorization.
Related
I got the temporary access token, serverAuthCode, web client id and its secret, i am trying to get refresh token from oathplayground but i am getting invalid grant error. I have rechecked the tokens many times but still getting same error. Here are the screenshots :
What can i do to get the refresh tokens ? For more information, i am using react-native-google-sign-in library, from this library, i got the 1. access_token, ServerAuthCode. From Google Developers console, i got the 1.Web Client Id 2.Client Secret , I am using these credentials inside the react native app and i am getting the tokens successfully, but the problem is sometimes they work and most of the times i get "invalid credentials" error when i try to use the access token, it is because the access token is expired, that's why i need the refresh token. If you have any idea why i am not able to get refresh token or how to get refresh token using another method, please let me know.
I understood what i was doing wrong, i was using the serverAuthCode that was not new, it should be the latest one + the first time when you allowed the app for permissions, and it will work only first time, after you have exchanged it for a refresh token, it will not work again and will always give you grant_error. So after getting the refresh token you can get a new refreshed access token. I was using react-native-google-sign-in and was in need of refreshed token, read below to know more about the same.
For React-native-google-sign-in :
The access token you will receive from GoogleSignin.getTokens(); will only last for about an hour, to get a new access_token we need to send serverAuthCode to https://oauth2.googleapis.com/token with fields : client_id, client_secret, code(this is serverAuthCode), grant_type(its value should be authorization_code), redirect_uri(can set it from developers console). Remember to only use the serverAuthCode that you get on your first attempt when you just allowed your app for the permissions FIRST TIME otherwise you will get grant_error every time. After getting the refresh_token, we need to get the new access_token using refresh token that we just got, so now just replace the value of grant_type from authorization_code to refresh_token and also replace the value of code field to refresh_token , fill its value and send a post request to the same url, you will get a fresh access_tokenthat will be valid for 1 hour.
We are creating an application with Ionic framework as front-end and Ruby on Rails as back-end. We are able to link Gmail account in our app. Account linking is working fine, we get serverAuthCode from front-end and then using that we get refresh token and we are able to fetch emails with that refresh token at first attempt. But within seconds, it get expired or revoked. Getting the following issue:
Signet::AuthorizationError (Authorization failed. Server message:
{
"error" : "invalid_grant",
"error_description" : "Token has been expired or revoked."
})
It seems like, refresh token itself is expiring in seconds. Does anyone have any idea about how to fix it?
Update:
Existing code looks like this:
class User
def authentication(linked_account)
client = Signet::OAuth2::Client.new(
authorization_uri: 'https://accounts.google.com/o/oauth2/auth',
token_credential_uri: Rails.application.secrets.token_credential_uri,
client_id: Rails.application.secrets.google_client_id,
client_secret: Rails.application.secrets.google_client_secret,
scope: 'https://www.googleapis.com/auth/gmail.readonly, https://www.googleapis.com/auth/userinfo.email, https://www.googleapis.com/auth/userinfo.profile',
redirect_uri: Rails.application.secrets.redirect_uri,
refresh_token: linked_account[:refresh_token]
)
client.update!(access_token: linked_account.token, expires_at: linked_account.expires_at)
return AccessToken.new(linked_account.token) unless client.expired?
auth.fetch_access_token!
end
def get_email(linked_account)
auth = authentication(linked_account)
gmail = Google::Apis::GmailV1::GmailService.new
gmail.client_options.application_name = User::APPLICATION_NAME
gmail.authorization = AccessToken.new(linked_account.token)
query = "(is:inbox OR is:sent)"
gmail.list_user_messages(linked_account[:uid], q: "#{query}")
## Getting error over here ^^
end
end // class end
class AccessToken
attr_reader :token
def initialize(token)
#token = token
end
def apply!(headers)
headers['Authorization'] = "Bearer #{#token}"
end
end
Reference link: https://github.com/google/google-api-ruby-client/issues/296
From what I can guess the issue seems to be on these two lines. The way token expiry is being checked and the new token is being generated. It would be great if there is minimal reproducible code.
return AccessToken.new(linked_account.token) unless client.expired?
auth.fetch_access_token!
Here is how I get my access token:
def self.access_token(refresh_token)
Cache.fetch(refresh_token, expires_in: 60.minutes) do
url = GoogleService::TOKEN_CREDENTIAL_URI
# p.s. TOKEN_CREDENTIAL_URI = 'https://www.googleapis.com/oauth2/v4/token'
_, response = Request.post(
url,
payload: {
"client_id": GoogleService::CLIENT_ID,
"client_secret": GoogleService::CLIENT_SECRET,
"refresh_token": refresh_token,
"grant_type": "refresh_token"
}
)
response['access_token']
end
end
And then use this access token for any purpose. Let me know how it goes and also if you are able to create a reproducible version of the API. That will be great.
Have you tried refreshing the access token with the refresh token? You can catch the error and retry.
Something like this:
begin
gmail.list_user_messages(linked_account[:uid], q: "#{query}")
rescue Google::Apis::AuthorizationError => exception
client.refresh!
retry
end
Not enough code is posted, but what is posted looks wrong.
linked_account is not defined
Nowhere is it shown that linked_account.token is ever updated (or set, for that matter). It needs to be updated when the refresh_token is used to get a new access token.
auth appears to be undefined in the line auth.fetch_access_token!
GmailService#authorization= takes a Signet::OAuth2::Client not an AccessToken.
Probably what is happening is that you have a valid access token in linked_account.token until you call client.update!, which fetches a new access token and invalidates the old one. But since you never update linked_account, future calls fail until you go through the code path that resets it.
You only need to call client.update! if the access token has expired, and if it has expired and you get a new one, you need to store that new one in linked_account.token.
The thought that the refresh token will never expire is actually a misunderstanding. The actual scene is that the server issues a short-lived access token and a long lived refresh token. So in reality what happens is that the access token can be regained using the long lived refresh tokens but yes, you will have to request a new refresh token (as it expires too !). For example; you may treat refresh tokens as if they never expire. However on sign-in check for a new one, in case the user revokes the refresh token, in this scenario, Google will provide a new refresh token on sign-in so just update the refresh token.
Now the condition can be that the user revokes access to your application. In this case, the refresh token will expire (or I should actually say that it would become an unauthorized one). So if that is the scenario in your case, you will have to think on avoiding the revoking of access for the application.
For better understanding of it, you may refer to this document and even OAuth 2.0 documentation.
There are several reasons why a refresh token would stop working.
It gets to old refresh tokens expire after six months if not used.
A user can reauthecate your application and get a new refresh token both refresh tokens will work you can have a max of fifty outstanding refresh tokens then the first will stop working.
the user can revoke your access.
Wakey daylight savings time bug of 2015. (we wont talk about that)
Gmail and reset password.
This is mostly like due to a password reset. OAuth grants with the gmail scopes are revoked when a user changes their password.
See Automatic OAuth 2.0 token revocation upon password change
In general, users can revoke grants at any time. You should be able to handle that case gracefully and alert the user that they need to reauthorize if they wish to continue using the functionality provided.
You have been doing a lot of testing i would guess are you saving the newest refresh token? If not then you may be using old refresh tokens and the will stop working. (number 2)
In my case, only youtube upload api raise
Unauthorized (Google::Apis::AuthorizationError)
and other api, like list videos api work well
it's because i use new google account and have not up video
i manually up video in youtube web, youtube require me create "channel"
and I try youtube up api again, it work
I guess it's because youtube has channel to up
Using Rails 4 and Koala gem version 2.
I have my personal Facebook page (not profile).
When I am publishing a new post in my website I want to automatically publish it on my facebook page as well.
I am using Koala gem but I have some problem with access tokens.
Visiting https://developers.facebook.com/tools/explorer/ I get a short-live token. This token expires after only 2 hours.
My goal is to obtain a long-live token.
I have created a new Facebook app and I have obtained a client-id and client-secret.
Visiting this https://graph.facebook.com/oauth/access_token?client_id=MY-CLIENT-ID&client_secret=MY-CLIENT-SECRET&grant_type=fb_exchange_token&fb_exchange_token=MY-SHORT-LIVE-TOKEN I get long-live token.
Now I can use my long-live token to publish on my page:
user = Koala::Facebook::API.new long_live_access_token
page_access_token = user.get_connections('me', 'accounts').first['access_token']
page = Koala::Facebook::API.new page_access_token
page.put_connections("me", "feed", message: "I am posting on my page!ok!")
It seems to work, but my problems is that the long-live token expires in 60 days so I need to refresh it.
I have found no solution to refresh a long-live token. It is clear that I can't repeat the entire procedure every 60 days!
Ideas?
From the official docs:
These tokens (long-lived) will be refreshed once per day when the
person using your app makes a request to Facebook's servers. If no
requests are made, the token will expire after about 60 days and the
person will have to go through the login flow again to get a new
token.
The token that never expires is a page token.
I'm having issues with Google OAuth2 in iOS; I'm getting an "invalid_grant" error. I am doing the following steps:
I created the project and Credential ( iOS app ) Google Console;
I did request the CODE;
I did request the access token (working well);
10 minutes before the expiry of the access token , I do request a refresh token.
The problem is intermittent . Sometimes the request for refresh ( refresh_token ) returns " invalid_grant " and so the access_token becomes invalid and my application just stops .
If forcing the user login to generate a new access_token and refresh_token not work. I have to revoke the permissions of the account and try again.
What I need is access to IMAP and SMTP Gmail . If I check the access_token ( https://www.googleapis.com/oauth2/v1/tokeninfo ) is active and valid , but the IMAP and SMTP denies access.
I'm actually thinking of going back to the login username and password . The service is very unstable for not having the same reaction . I'm sure I'm not bursting any limitations and been the message " invalid_grant " would at least not appropriate.
Please , any employee of Google, HELP ME !
Thank you.
I was facing this problem as well. I wasn't doing anything with IMAP, but I was getting an invalid_grant pretty frequently when trying to handle auth. Eventually I got things working using the following settings:
authentication.refreshToken = savedRefreshToken;
authentication.accessToken = savedAccessToken;
authentication.additionalTokenRequestParameters = #{#"access_type":#"offline"};
I think it was mainly that last one that did the trick. I found it somewhere in the Google documentation, but I didn't save where. Their docs are pretty messy.
I have a Rails (3.2.11) application that allows users to post updates to their LinkedIn profiles. I'm currently using the omniauth-linkedin gem to capture the initial user authentication and the linkedin gem to post the updates. The problem I'm having is that LinkedIn access tokens expire after 60 days, but according to their documentation a token can be refreshed prior to expiration without a user having to reauthorize the application.
I've looked at the LinkedIn Tips and Tricks, Authentication Overview, and tons of posts on StackOverflow - this, this, and this being just a couple of examples - and I still can't find any answers.
After a user authorizes the app (via omniauth-linkedin), I save the access_token and secret returned to me from LinkedIn. I need to figure out how I can use the still-valid access_token to refresh it and extend the expiration date another 60 days.
I've tried using the authenticate endpoint from LinkedIn (where tokens.access_token is the currently valid token):
url = "https//www.linkedin.com/uas/oauth/authenticate?oauth_token=" + tokens.access_token
result = RestClient.post(url, {oauth_callback: "http://localhost:3000/users/auth/linkedin/callback"})
but I get an undefined method 'request_uri' for #<URI::Generic:0x1b144d20> Exception.
I've tried using the OAuth::Consumer client (where tokens.access_token and tokens.token_secret are the currently valid tokens):
configuration = { site: 'https://api.linkedin.com', authorize_path: '/uas/oauth/authenticate',
request_token_path: '/uas/oauth/requestToken', access_token_path: '/uas/oauth/accessToken' }
consumer = OAuth::Consumer.new(ENV['LINKEDIN_APP_ID'], ENV['LINKEDIN_SECRET'], configuration)
access_token = OAuth::AccessToken.new(consumer, tokens.access_token, tokens.token_secret)
but this just gives me back the same access_token and secret.
In the end, I'd love to be able to leverage the existing omniauth-linkedin gem functionality to handle this refresh, any idea if this is possible? Thanks!
In your second approach (using the OAuth::Consumer client and passing in your existing access token and secret) should refresh the token for you. As the documentation states, as long as the current user is logged into LinkedIn.com and the current access token hasn't expired yet, the token will be refreshed.
That doesn't mean necessarily that you'll get a new token. You may get the same one as you had before. The key difference is that the lifespan of the token should 60 days. You can verify this by check the value of oauth_expires_in parameter. It should be set to 5184000.
This blog post goes into detail about refreshing the token: https://developer.linkedin.com/blog/tips-and-tricks-refreshing-access-token