Ted Scheckler
Ted Scheckler

Reputation: 1521

Google OAuth2 Refresh Token with JavaScript

I have read documentation on refresh tokens but I am having a difficult time applying them to my code.

I think the correct approach is the php generates a refresh token, sends that to the client, then the client stops using the id_token and only makes requests with the refresh token? But this seems like it just defeats the purpose of token expiration.

How do I deal with token expiration and use refresh token in this scenario:

I'm using https://apis.google.com/js/platform.js to authenticate google accounts with:

<div class="g-signin2" data-onsuccess="onSignIn"></div>

Then with onSignIn, using ajax to get some data from a server after sign in with id_token being checked on the back-end server with php:

function onSignIn(googleUser) {
    var profile = googleUser.getBasicProfile();
    id_token = googleUser.getAuthResponse().id_token;
    angular.element(document.getElementById('data_controller')).scope().get_data(); 
};

The relevant Angular JavaScript is:

angular.module('myApp', ['ngDialog']);
angular.module('myApp').controller('data_controller', function($scope, $q, $http, ngDialog) {
    $scope.get_data = function() {
        $http({
            headers: { "Content-Type": "application/x-www-form-urlencoded", "id_token": id_token },
            url: "http://myserver/api/application.php",
            method: "POST",
            data: {}
        })
        .then(function successCallback(response) {
            $scope.my_data = response.data.results;
            $scope.token_used = id_token;
            console.log(response.data);
        });
    }
});

This works fine, but once the id_token expires after an hour, the ajax will fail.

On http://myserver/api/application.php I am checking the token provided in the header of the request with:

https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" . $id_token;

If the client reloads the page, everything works fine as google automatically fetches a new id_token.

Upvotes: 0

Views: 940

Answers (1)

Ted Scheckler
Ted Scheckler

Reputation: 1521

I was using the token incorrectly.

I changed:

headers: { "Content-Type": "application/x-www-form-urlencoded", "id_token": id_token },

To:

headers: { "Content-Type": "application/x-www-form-urlencoded", "id_token": gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().id_token },

This way it sends the current token. I hadn't realized the token automatically refreshes in the background. I was sending the original token each time, so once it expired the application would fail.

Upvotes: 2

Related Questions