Google API authorization in Node.js

Hello, as mentioned in previous post I’ve recently started re-implementing Youtube Queuer functionality in JavaScript. Since I was starting from scratch essentially, the first thing I’ve taken care of was Google API authorization.

Setup

As title suggests, you should have Node.js installed on your machine. Next, go to an empty directory, where the project will be located. Run npm init in the same directory so the package.json is created, then install Express and Google API modules by running npm install express googleapis --save.

Code

You need to create an entry point for Node.js, in my case it was a file named main.js. Make sure that package.json contains this entry:

{
  ...
  "scripts": {
    "start": "node main.js"
  },
  ...
}

Now, the sole authorization code:

var google = require('googleapis');
var authConfig = require('./google-auth-config');

var authService = {};

var OAuth2 = google.auth.OAuth2;

var scopes = [
    'https://www.googleapis.com/auth/youtube',
    'https://www.googleapis.com/auth/youtube.force-ssl'
];

authService.configure = function(port) {

    var oauth2Client = new OAuth2(
        authConfig.clientId,
        authConfig.clientSecret,
        `http://localhost:${port}/Authorized`
    );

    authService.authorizationUrl = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: scopes
    });

    authService.oauthClient = oauth2Client;
}

module.exports = authService;

In my case, the scopes relate to Youtube, as I am utilizing access to it in my app, change it to fit your needs. Next important thing is the import of authConfig. The imported object contains clientId and clientSecret, which can be obtained in Google developer’s console (OAuth2 client is needed). Template of the file looks like this:

var config = {};

config.clientId = 'YOUR_CLIENT_ID';
config.clientSecret = 'YOUR_CLIENT_ID';

module.exports = config;

Now, we need to fill in main.js, so that it handles authorization request. Here is the code:

var googleAuth = require('./googleAuth');
var express = require('express');
var path = require('path');

var app = express();

var port = 8080;
googleAuth.configure(port);

app.get('/', (req, res) => {
    res.send('This is root');
})

app.get('/authorize', (req, res) => {
    res.redirect(googleAuth.authorizationUrl);
});

app.get('/authorized', (req, res) => {
    googleAuth.oauthClient.getToken(req.query.code, function(err, tokens) {
        if (err) {
            console.log(err);
            return;
        }
        googleAuth.oauthClient.setCredentials(tokens);
        res.send("Authorization successful");
    });
});

app.listen(port, function() {
    console.log(`App listening on port ${port}!`)
});

This sets up simple routing, which enables authorization of your app. Now, run npm start from the application directory. If everything’s fine, you should see the text: App listening on port 8080 in console. Then, go to your browser, type http://localhost:8080/authorize as the URL. You should see a consent screen, familiar to this:
ConsentScreen.png

That’s it for Google API authorization.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s