Search code examples
node.jspassport.jsgoogle-contacts-apigoogle-people-api

Google People API: Request had invalid authentication credentials - Authorization Bearer header not setting up


I am trying to implement this Google People api for a chat application that I am working on. people API docs has only this example - https://github.com/googleworkspace/node-samples/blob/master/people/quickstart/index.js

I made some changes to use integrate it with my project.

// imports

const app = express();
app.use(cookieParser());

const SCOPES = ['https://www.googleapis.com/auth/contacts.readonly'];
const people = google.people('v1');

let credentials, oAuth2Client;
fs.readFile('./client_secret.json', async (err, content) => {
    if (err) return console.error(err);
    credentials = JSON.parse(content);

    const { client_secret, client_id, redirect_uris } = credentials.web;
    oAuth2Client = new google.auth.OAuth2(
        client_id, client_secret, redirect_uris[1]);
});


app.get("/auth/google", (req, res) => {
    console.log(req.cookies);
    res.cookie("sample_cookie", "sample_value");

    const authUrl = oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES,
    });

    console.log('Authorize this app by visiting this url:', authUrl);
    res.redirect(authUrl);
});

app.get("/contacts", (req, resp) => {
    if (req.cookies.access_token && req.cookies.refresh_token) {

        const token = {
            access_token: req.cookies.access_token,
            refresh_token: req.cookies.refresh_token,
            scope: req.cookies.scope,
            token_type: "Bearer",
            expiry_date: req.cookies.expiry_date,
        }

        oAuth2Client.setCredentials(token);

        const service = google.people({ version: 'v1', oAuth2Client });
        service.people.connections.list({
            resourceName: 'people/me',
            pageSize: 10,
            personFields: 'names,emailAddresses,phoneNumbers',
        }, (err, res) => {
            if (err) return resp.send(err);
            const connections = res.data.connections;
            
            if (connections) {
                connections.forEach((person) => {
                    if (person.names && person.names.length > 0) {
                        resp.write(person.names);
                    } else {
                        resp.write('No display name found for connection.');
                    }
                });
            } else {
                resp.write('No connections found.');
            }
            resp.end();
        });
    } else {
        res.send("Something's wrong yet.")
    }
})

app.get(["/auth/google/callback", "authorized"], async (req, res) => {
    const code = req.query.code;

    oAuth2Client.getToken(code, (err, token) => {
        if (err) return console.error('Error retrieving access token', err);
        oAuth2Client.setCredentials(token);

        res.cookie("access_token", token.access_token);
        res.cookie("refresh_token", token.refresh_token);
        res.cookie("scope", token.scope);
        res.cookie("token_type", token.token_type);
        res.cookie("expiry_date", token.expiry_date);

        res.send("Done.")
    })
})

app.listen(3000, () => {
    console.log("running");
})

but I am getting 401: unauthorized. All the changes that I made to the former (Google) example is just that instead of saving details to token, I am saving them as cookies, and I added routes to access it from browser. The example provided by Google works as expected. The changes I made works as well till the authorization point but when trying to access contacts route it returns the following response.

this is the response I am geeting (only included details that I believe to be necessary):

{
    "response": {
        "config": {
            "oAuth2Client": {
                "credentials": {
                    "access_token": "my_access_token",
                    "refresh_token": "my_refresh_token",
                    "scope": "https://www.googleapis.com/auth/contacts.readonly",
                    "token_type": "Bearer",
                    "expiry_date": 1609256514576
                },
                "redirectUri": "http://localhost:3000/auth/google/callback",
            },
            "url": "https://people.googleapis.com/v1/people/me/connections?pageSize=10&personFields=names%2CemailAddresses%2CphoneNumbers",
            "method": "GET",
            "headers": {
                "Accept-Encoding": "gzip",
                "User-Agent": "google-api-nodejs-client/0.7.2 (gzip)",
                "Accept": "application/json"
            },
        },
        "data": {
            "error": {
                "code": 401,
                "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
                "errors": [{
                    "message": "Login Required.",
                    "domain": "global",
                    "reason": "required",
                    "location": "Authorization",
                    "locationType": "header"
                }],
                "status": "UNAUTHENTICATED"
            }
        },...

I tried to debug the code. I can't catch anything. But one thing I noticed is that in the above response I do not have Authorization header set. In successful API request from the google docs example, I receive

{
    "config": {
        "url": "https://people.googleapis.com/v1/people/me/connections?pageSize=10&personFields=names%2CemailAddresses%2CphoneNumbers",
        "method": "GET",
        "headers": {
            "Accept-Encoding": "gzip",
            "User-Agent": "google-api-nodejs-client/0.7.2 (gzip)",
            "Authorization": "Bearer access-code",
            "Accept": "application/json"
        },
    },
    "data": {
        "connections": [{...

I Don't get why my code isn't setting the Authorization header, also OAuthClient and credentials field is not present in this successful response. If instead of people api I try something like below in contacts route or make a GET request with Bearer token in postman I get the response correctly.

let bearer = `Bearer ${req.cookies.access_token}`;
request({
    url: 'https://people.googleapis.com/v1/people/me/connections?pageSize=10&personFields=names%2CemailAddresses%2CphoneNumbers',
    headers: {
        'Authorization': bearer
    }}, (err, res) => {
        if (err) {
            console.error(err);
         } else {
            resp.send(res);
         }
    }
);

I recieve the response correctly. But I do not want to do it this way. I can't figure out what's wrong with my code or if someone can provide any other working example... I also tried using passport.js and I get the same 401 unauthorized error.

// passport-setup.js
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.serializeUser(function (user, done) {
    done(null, user);
});

passport.deserializeUser(function (user, done) {
    done(null, user);
});

passport.use(new GoogleStrategy({
    clientID: "client-id",
    clientSecret: "client-secret",
    callbackURL: "http://localhost:3000/auth/google/callback",
    passReqToCallback: true
},
    function (req, accessToken, refreshToken, otherTokenDetails, profile, done) {
        req.session.accessToken = accessToken;
        req.session.refreshToken = refreshToken;
        req.session.scope = otherTokenDetails.scope;
        req.session.token_type = otherTokenDetails.token_type;
        req.session.expiry_date = new Date().getTime() + otherTokenDetails.expires_in;

        return done(null, profile);
    }
));

index.js
// importing express, cors, bodyParser, passport, cookieSession, passport setup and googleapis

const app = express();
const people = google.people('v1');

// app.use(cors, bodyParser, cookieSession, passport init and session)

const isLoggedIn = (req, res, next) => {
    if (req.user) {
        next();
    }
    else {
        res.sendStatus(401);
    }
}

app.get("/success", isLoggedIn, (req, resp) => {
    const oAuth2Client = new google.auth.OAuth2(id, secret and url...)

    const token = {
        access_token: req.session.accessToken,
        refresh_token: req.session.refreshToken,
        scope: req.session.scope,
        token_type: req.session.token_type,
        expiry_date: req.session.expiry_date,
    }

    oAuth2Client.setCredentials(token);

    const service = google.people({ version: 'v1', oAuth2Client });
    service.people.connections.list({
        resourceName: 'people/me',
        pageSize: 10,
        personFields: 'names,emailAddresses,phoneNumbers',
    }, (err, res) => {
        if (err) return resp.send(err);
        const connections = res.data.connections;
        
        if (connections) {
            console.log('Connections:');
            connections.forEach((person) => {
                if (person.names && person.names.length > 0) {
                    resp.write(person.names);
                } else {
                    resp.write('No display name found for connection.');
                }
            });
        } else {
            resp.write("No connections.");
        }
        res.end();
    });
})

app.get('/auth/google',
    passport.authenticate('google', {
        scope: ['profile', 'email', 'https://www.googleapis.com/auth/contacts'],
        accessType: 'offline',
        prompt: 'consent',
    }));

app.get('/auth/google/callback',
    passport.authenticate('google', { failureRedirect: '/login' }),
    function (req, res) {
        res.redirect('/success');
    });

app.listen(3000, () => console.log("Server is up and running on port 3000."));

I have checked almost every similar Stack Overflow answer and GitHub issues. Nothing seems to work out.


Solution

  • The name for the second parameter that is passed into google.people is auth. In JavaScript you can write {auth: auth} as simply {auth}. In the example provided by google, the name of the variable is same as the field name, That's why it is directly supplied as auth

    const service = google.people({ version: 'v1', auth });
    

    But your variable name is different than the field name. so change the name or just replace this one line with

    const service = google.people({ version: 'v1', auth: oAuth2Client });
    

    It is expecting auth as the second property but it receives a property wth name oAuth2Client that's why it is not working.