OAuth2 refresh token - how to refresh? - oauth

I'm writing a program that automates some actions with my Gmail account (using Ruby). I generate a callback URL and go to it, which gives me an auth code. Then, I request a refresh token using the auth code.
Now, after the refresh token expires, I was under the impression I can just grab another refresh token using the original auth code. But it seems I keep having to get a new auth code - which is frustrating because I'm hard coding the auth code in my script right now. Is this normal? Am I misunderstanding refresh tokens?

consider code as one-time-password to get a access_token. With access_token you are also getting refresh_token, both have expiration date set - refresh_token is valid for longer time, but if it expires you have to begin whole flow from the very beginning ( getting code )

Related

Sign In With Apple refresh token validation only access token returned

I'm using the AppleAuth npm package in my server to submit token requests to Apple's servers during the sign in with Apple process. (This is based off the sample server code provided with the sign_in_with_apple package in pub.dev) I have no issues submitting the authorization code to get my first access and refresh tokens.
However, when trying to test how my app would get a new refresh token, when I submit a POST request to https://appleid.apple.com/auth/token with the grant_type set to refresh_token the response I get is different than from having the grant_type set to authorization_code.
I looked at the source code of the package, and for its AppleAuth(myConfig).refreshToken(myRefreshToken) (<- pseudo code lol) the only difference in the POST payload is:
{
grant_type: 'refresh_token', // instead of grant_type: 'authorization_code'
refresh_token: refreshToken, // instead of code: authorizationCode
... // other params
}
While the initial request with authorization code returns both an access token and a refresh token, for some reason the refresh token request is only returning the access token. I really don't think it's the package causing the error, nor can I see how my code would be the source either, since the above code is the only difference.
I tried passing the access token that it returns in a new refresh token request in order to test that I can get new refresh tokens whenever necessary in the future, but it returns a 400 status error.
Am I missing something here? Is there a reason the refresh token request returns no new refresh token? Or am I missing something entirely about how the process/flow is supposed to work? I am trying to do this for the "check the refresh token once daily to confirm the user is still in good standing with Apple's servers" part of the process.
I've really been stuck on what to do at this point. I can save the identity_token.sub field in my database to check whether my user is signed in, but of course I want to make sure my user's apple ID is still valid with apple, and that they haven't revoked access. Could it be that because I tried to get a new refresh_token too soon Apple only returned the access_token?
Oh also, the app itself is a Flutter app and I am testing all of this on my iPhone 11 so it's not an Android/Web flow.
Whether you get a new 'rolling / rotating' refresh token in a refresh token grant response is generally vendor specific:
You may get a new refresh token occasionally but not always
The primary purpose of this message is to get a new access token, not a new refresh token
In terms of token handling, the client should update its tokens similarly to the saveTokens method in this sample of mine.
I've not used Sign In with Apple but I suspect proceeding as follows would be the simplest solution:
Keep access tokens short lived: no more than 60 minutes
This forces a frequent token refresh, which by default is very quick
If the user's Apple Id is revoked I would expect this to return an invalid_grant response

oauthplayground invalid grant, trying to get refresh token google oauth

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.

Get refresh token with Auth0

I am developing an API. I implemented register, login, and Facebook auth using Auth0.
My token expires after one day, and I need to get my refresh token to sign in the user again without requiring its credentials again. I have to make a call to /authorize with these parametrs [sic]:
GET https://YOUR_AUTH0_DOMAIN/authorize?
audience=API_IDENTIFIER&
scope=SCOPE&
response_type=code&
client_id=YOUR_CLIENT_ID&
redirect_uri=https://YOUR_APP/callback&
state=STATE
but I get this error Image
The GET response should give me a code, which I would use to get my refresh token making another GET request on /oauth/token like that: Image
Does anyone have any idea how to get over the first step?
Have you tried using curl to get access token and refresh token and then refresh outside of your app? The following link has very detailed instruction on how to do that with auth0.
https://auth0.com/learn/refresh-tokens/

Google::Apis::AuthorizationError (Unauthorized)

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

Myob - AccountRight Live Api v2 Skip login screen

I am using accountright Live api v2 by MYOB. I want to get access token without going to login screen. When I send a CURL request to obtain access token i am redirected to myob login screen, how to skip that? The request I am sending is to url:
'https://secure.myob.com/oauth2/v2/authorize'
and params sent are:
Array
(
[client_id] => xxxxxxxxxxxxxxxxxxxxxxxx
[client_secret] => xxxxxxxxxxxxxxxxxxxxx
[scope] => CompanyFile
[code] => XXXXXXXXXXXXXX
[redirect_uri] => http://myappcodeonmydomain.com
[grant_type] => authorization_code
)
After your initial request to the API to get the access token, you should also be provided with a refresh token. Access tokens expire after a period of time, and need to be refreshed.
From the Refreshing an Access Token section in the Authentication Documentation:
Access tokens have a limited life span and when you receive one you'll
also receive an Expiry Time for it and a Refresh Token. Once your
access token expires it can no longer be used to access the API. So
you'll need to trigger a refresh. You do this by POSTing the following
parameters:
'client_id' // your API Key
'client_secret' // your API Secret
'refresh_token' // your refresh token
'grant_type' // this should say refresh_token
To this url: https://secure.myob.com/oauth2/v1/authorize
Note: while the data is formatted into a URL Query String you do not
pass the information via the URL (that would be a GET request), you
must pass the query string in the body and POST this to
https://secure.myob.com/oauth2/v1/authorize
As an example, I store my access and refresh tokens in a database, along with an expected expiry time 10 minutes in the future. If a request is going to be made after that time, I call the refresh procedure to update the access token, and am able to proceed on my merry way without needing to show the login prompt each time.
You do need to have it shown at least once to find out which user is logging in, and the GUID of the Company File to connect to.
If you are talking about the first time auth, then there is no way to do it. You have to redirect the user to the login page by returning the url.
If you are talking about refresh the token, then it's easy.
I'm not sure how you implement the API connection. I'm using the myob ruby sdk.
The ruby sdk is so easy to use and it will do all those auth operations for you.
:)

Resources