Skip to content

Instantly share code, notes, and snippets.

@forficate
Created September 15, 2015 00:42
Show Gist options
  • Save forficate/fd5ec72b21eafad6592c to your computer and use it in GitHub Desktop.
Save forficate/fd5ec72b21eafad6592c to your computer and use it in GitHub Desktop.
# Get a refresh token for a client.
We use offline so we can access the account without the user needing to reauthenticate https://developers.google.com/identity/protocols/OAuth2WebServer
Also see the Web server applications sequence diagram at Web server applications
```
client_id=""
scopes="email profile"
csrf="some csrf token to validate"
redirect_uri="http://example.com/oauthcallback"
curl -i -X POST "https://accounts.google.com/o/oauth2/auth" \
--data "scope=$scopes&state=$csrf&redirect_uri=$redirect_uri&response_type=code&client_id=$client_id&approval_prompt=force,access_type=offline"
```
# Google will call the url redirect_uri specified with 2 response types
* http://example.com/oauthcallback?error=access_denied
* https://oauth2-login-demo.appspot.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7
On failure we see an error param. On Succes we see an auth param. This is an authorization code response. It is recommended
that the redirect_uri is a server endpoint which processes the authorization code then redirect. If the page is an
html page you will leak the authorization code in the url via access logs + to external hosts via 'HTTP REFERER' header.
Now you have the authorization code request an access token. The first time we call this we get the refresh token, you should persist this so we don't need to do the auth step again.
```
curl -i -X POST "https://www.googleapis.com/oauth2/v3/token" \
--data "code=$previous_authorization_code&client_id=$client_id&client_secret=$client_secret&redirect_uri=$redirect_uri&grant_type=authorization_code"
```
The redirect_uri endpoint should see the following response:
```
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"refresh_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer"
}
```
Obtaining a new token if your access token expires with our refresh token:
```
curl -i -X POST "https://www.googleapis.com/oauth2/v3/token" \
--data "client_id=$client_id&client_secret=$client_secret&refresh_token=$refresh_token&grant_type=refresh_token"
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment