10

I am doing server side OAuth following this guide.

I successfully completed the OAuth, but am not getting a refresh_token in the step Exchange authorization code for refresh and access tokens:

Request:

POST /o/oauth2/token HTTP/1.1
HOST: accounts.google.com
content-type: application/x-www-form-urlencoded
content-length: 260

code=4/KEOuzih9jwfnHj7Rl1DeqHhcJF0goKPwtwR5IQ09ieg&
client_id=****.apps.googleusercontent.com&
client_secret=****&
redirect_uri=http%3A%2F%2Flocalhost%3A8000%2FsSignIn.html&
grant_type=authorization_code

Response:

{
  "access_token" : "****",
  "expires_in" : 3580,
  "token_type" : "Bearer"
}

Am I missing something?

stvar
  • 6,551
  • 2
  • 13
  • 28
Abhishek Gupta
  • 6,465
  • 10
  • 50
  • 82

2 Answers2

20

Two things needed to be done:

  1. To get refresh token, you have to pass access_type=offline as query parameter to the oauth start request. This will make sure you get the refresh token when doing the oauth for the first time for the account.
  2. To get the refresh token on doing the oauth again and again for the same account, you have to pass prompt=consent as query parameter to the oauth start request.

Reference: https://developers.google.com/identity/protocols/OAuth2WebServer#offline

Abhishek Gupta
  • 6,465
  • 10
  • 50
  • 82
  • 1
    Thanks Abhishek! I was passing the access_type offline but I did not have the prompt consent enabled. Now it returns the refresh token . – jremi Feb 25 '18 at 00:21
1

The support documents on this is really bad and incomplete.

This is the php code. But these setting produce a Refresh Token.

$client->setIncludeGrantedScopes(true);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
Dharman
  • 30,962
  • 25
  • 85
  • 135