Skip to main content

Google

Register your app in Google's Dashboard

To use the Google Provider you will need a client id and a client secret. You will get them while following the process to setup Google OAuth 2.0 for your application. Follow the instructions in the following link:

info

When asked for an origin URL, insert the origin of the url in which your app is hosted.

Examples:

  • http://localhost:3000
  • https://www.example.com

When asked for a redirect URL (or callback URL), insert [http or https]://[origin]/[your route for Google authentication]

Examples:

  • http://localhost:8000/auth/google
  • https://www.example.com/api/login/google
  • https://www.example.com/godel/russell/myGoogle

Google's official guide (Follow the guide until you get a client id and client secret and setup a callback. Don't worry about the rest, Gatekeeper will take care of that): https://support.google.com/cloud/answer/6158849

Google Provider

Options

Option nameDescriptionDefault valueRequired?
clientIdYour Google OAuth client idYes
clientSecretYour Google OAuth client secretYes
callbackURLThe URL that will serve as callback for Google OAuthYes
scopeThe OAuth scopes that will be granted to the access token['profile']No
danger

To the callbackURL option you must provide the URL you provided when asked for a redirect (or callback) URL when registering your Google OAuth app (if you followed our recommendation, present in the opening paragraph of this page, just provide the URL from which you will be using your provider)

Handler

The Google Provider passes three parameters to the handler:

  • refresh_token: The OAuth refres token. It is usually only given the first time a user signs-in to your application
  • access_token: The OAuth access token.
  • profile: The information of the Google user.

Errors

The predefined errors of this provider are:

  • UserNotFound

Examples

Example #1

Create a Google Provider

import gatekeeper from 'gatekeeper-authentication'
import { GoogleProvider } from 'gatekeeper-authentication/providers/google'

const GoogleAuth = new GoogleProvider({
clientId: '<YOUR GOOGLE CLIENT ID>',
clientSecret: '<YOUR GOOGLE CLIENT SECRET>',
callbackURL: 'https://yourdomainorlocalhost.com/auth/google'
}, function handler(refresh_token, access_token, profile) => {
const user = User.findOne({ googleId: profile.sub })

if (user == null) {
// For example, if the user does not exist, create it
User.create({
username: profile.name,
profilePicture: profile.picture
});
}

return user;
});

Login with Google Provider

warning

Important: When using the Google provider on login routes, make sure you use gatekeeper.authenticateWithProvider(yourGoogleProvider) in a GET route, as the user will be redirected to Google's sign in page

router.get(
'/auth/google',
gatekeeper.authenticateWithProvider(GoogleAuth), (req, res) => {
return res.redirect('/profile');
}
);