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:
When asked for an origin URL, insert the origin of the url in which your app is hosted.
Examples:
http://localhost:3000https://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/googlehttps://www.example.com/api/login/googlehttps://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 name | Description | Default value | Required? |
|---|---|---|---|
clientId | Your Google OAuth client id | Yes | |
clientSecret | Your Google OAuth client secret | Yes | |
callbackURL | The URL that will serve as callback for Google OAuth | Yes | |
scope | The OAuth scopes that will be granted to the access token | ['profile'] | No |
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 applicationaccess_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
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');
}
);