I can't get my refresh token with my code. I can only get my access token, token type etc., I have followed some tutorials like putting access_type=offline
on my login URL:
echo "<a href='https://accounts.google.com/o/oauth2/auth?" . "access_type=offline&client_id=123345555.apps.googleusercontent.com& " . "scope=https://www.googleapis.com/auth/calendar+https://www.googleapis.com/auth/plus.me&response_type=code& " . "redirect_uri=http://www.sample.com/sample.php&state=/profile'>Google</a>";
and my fields in getting the access token:
$fields=array( 'code'=> urlencode($authcode), 'client_id'=> urlencode($clientid), 'client_secret'=> urlencode($clientsecret), 'redirect_uri'=> urlencode($redirecturi), 'grant_type'=> 'authorization_code', );
but I can't get refresh_token, just the access_token, token_type, id_token and expires_in.
Let's move to Postman! Now go to Variables tab in this collection and paste your client Id and secret. Also enter appropriate scope. In Authorization tab of collection, just hit "Get New Access Token".
In order to get an access token with a refresh token, you just need to ask for the offline access type (for example in PHP: $client->setAccessType("offline"); ) and you will get it.
To use the refresh token, make a POST request to the service's token endpoint with grant_type=refresh_token , and include the refresh token as well as the client credentials if required.
Found out by adding this to your url parameters
approval_prompt=force
Update:
Use access_type=offline&prompt=consent
instead.
approval_prompt=force
no longer works https://github.com/googleapis/oauth2client/issues/453
If I may expand on user987361's answer:
From the offline access portion of the OAuth2.0 docs:
When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the
approval_prompt
parameter in the authorization code request, and set the value toforce
.
So, when you have already granted access, subsequent requests for a grant_type
of authorization_code
will not return the refresh_token
, even if access_type
was set to offline
in the query string of the consent page.
As stated in the quote above, in order to obtain a new refresh_token
after already receiving one, you will need to send your user back through the prompt, which you can do by setting approval_prompt
to force
.
Cheers,
PS This change was announced in a blog post as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With