Pages

Thursday, January 5, 2017

Building a Shared Calendar [Part 7]: Get an access token to interact with Google's Calendar API

Now we come to the crucial part of this whole project: programmatically create an event using Google's Calendar API. I will say that there is a google-auth-library that is released by Google but I could not get it to work. After playing and failing to get the samples working I decided to issue my own requests to the Calendar API.

First, we need a way to get an 'access token' that we can use when making the request. Luckily, Google provides an API Explorer that can act as the 'client' of any API. Go to the explorer and click on the 'Authorize Requests using OAuth 2.0' switch. This will initiate an OAuth flow and grant access to your calendars to the API explorer.


The UI will display the 'refresh token' of the client. You will need this so that the web site can always get a new access token to access the calendars (essentially, the web site will act as the API Explorer that has already been approved for access).

Now, on the web site add the refresh-token package which provides support for renewing google's access token:
var GoogleTokenProvider = require('refresh-token').GoogleTokenProvider;

var tokenProvider = new GoogleTokenProvider({
    refresh_token: process.env.GOOGLE_REFRESH_TOKEN,
    client_id: process.env.GOOGLE_CLIENT_ID,
    client_secret: process.env.GOOGLE_CLIENT_SECRET
});

function executeOAuthRequest(url, body, next) {
    tokenProvider.getToken(function (err, token) {
        if (err) {
            console.log('Failed to retrieve token', err);
            next(err);
        } else {
            // Ready to make a request to Google
        }
    });
}

Above is a helper function that we will use on the router that, given your refresh token, will use the GoogleTokenProvider to get an access token. The next post will finally use the access token to authenticate requests against the Calendar API.

Source code is available at bitbucket or you can play with the live test site.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.