Handling the Response
Google returns an access token to your application if the user grants your application the permissions it requested.
The access token is returned to your application in the fragment as part of the access_token parameter.
Since a fragment is not returned to the server, client-side script must parse the fragment and extract the value of the access_token parameter.
Other parameters included in the response include expires_in and token_type. These parameters describe the lifetime of the token in seconds,
and the kind of token that is being returned.
If the state parameter was included in the request, then it is also included in the response.
An example User Agent flow response is shown below:
https://oauth2-login-demo.appspot.com/oauthcallback#access_token=1/fFBGRNJru1FQd44AzqT3Zg&token_type=Bearer&expires_in=3600
Other fields may be included in the response. Your application should allow additional fields to be returned in the response. The set shown above is the minimum set.
Below is a Javascript snippet that parses the response and returns the parameters to the server.
This code is hosted at the https://oauth2-login-demo.appspot.com/oauthcallback URL.
// First, parse the query string
var params = {}, queryString = location.hash.substring(1),
regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// And send the token over to the server
var req = new XMLHttpRequest();
// consider using POST so query isn't logged
req.open('GET', 'https://' + window.location.host + '/catchtoken?' + queryString, true);
req.onreadystatechange = function (e) {
if (req.readyState == 4) {
if(req.status == 200){
window.location = params['state']
}
else if(req.status == 400) {
alert('There was an error processing the token.')
}
else {
alert('something else other than 200 was returned')
}
}
};
req.send(null);
This code sends the parameters received on the fragment to the server using XMLHttpRequest and writes the access token to local storage in the browser.
The latter is an optional step, and depends on whether or not the application requires other
Javascript code to make calls to a Google API. Also note that this code sends the parameters to the /accepttoken endpoint, and they are sent over an HTTPs channel.
Error Response
The Google Authorization Server returns an error if the user did not grant your application the permissions it requested.
The error is returned in the fragment.
An example error response is shown below:
https://oauth2-login-demo.appspot.com/oauthcallback#error=access_denied