Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// https://joshwright.com/tips/google-authentication-for-nodejs/
import { google } from 'googleapis';
const buildAuth = function () {
return new google.auth.OAuth2(
'0000000000000-xxxxxxxx.apps.googleusercontent.com', // clientId
'XXXXXXXXXXXXXXXXXXX', // clientSecret
'http://localhost:7777/google/callback', // redirect
);
};
app.get('/google/login', async (req, res) => {
const auth = buildAuth();
const url = auth.generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope: [
'https://www.googleapis.com/auth/userinfo.email',
'profile',
]
});
res.redirect(url);
});
app.get('/google/callback', async (req, res) => {
// get & set tokens
const { code } = req.query;
const auth = buildAuth();
const { tokens } = await auth.getToken(code);
auth.setCredentials(tokens);
// fetch the user's email
const peopleApi = google.people({version: 'v1', auth}).people;
const me = await peopleApi.get({
resourceName: 'people/me',
personFields: 'emailAddresses',
});
const address = me.data.emailAddresses.find(e => e.metadata.primary);
const email = address && address.value;
// TODO: login with email
res.redirect('/');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.