Authenticating Users and Protecting Routes
After learning what providers are, it is time to actually start using them!
Login
Suppose we want to implement Google sign-in in our application. First, we have to define a route we want the user to visit in order to do this. In this example we will use '/auth/google'.
To authenticate users whenever they get to this route, you just have to pass gatekeeper.authenticateWithProvider(theProviderYouWantToUse) to your router, like this:
Important: When using OAuth2 providers on login routes, make sure you use gatekeeper.authenticateWithProvider(yourProvider) in a GET route, as the user will be redirected to the provider's site to log in.
import gatekeeper from 'gatekeeper-authentication';
import GithubProvider from 'gatekeeper-authentication/providers/github';
const GithubAuth = new GithubProvider({
clientId: '<YOUR CLIENT ID>',
clientSecret: '<YOUR CLIENT SECRET>'
// The OAuth2 callback/redirect url you registered
// (the URL in which this provider will be used)
callbackURL: 'https://yourdomainorlocalhost.com/auth/github'
}, function handler(refresh_token, access_token, profile) => {
return profile;
});
/* Notice that we can use the prebuilt providers as many times as we want
to create multiple providers that do different things! */
const GithubWithSmileyFace = new GithubProvider({
clientId: '<YOUR CLIENT ID>',
clientSecret: '<YOUR CLIENT SECRET>'
// The OAuth2 callback/redirect url you registered
// (the URL in which this provider will be used)
callbackURL: 'https://yourdomainorlocalhost.com/auth/smiley/github'
}, function handler(refresh_token, access_token, profile) => {
profile.name = profile.name + ':D';
return profile;
});
router.get(
'/auth/smiley/github',
gatekeeper.authenticateWithProvider(GithubWithSmileyFace),
(req, res) => {
return res.json({ user: req.session.user, success: true });
}
);
router.get(
'/auth/github',
gatekeeper.authenticateWithProvider(GithubAuth),
(req, res) => {
return res.json({ user: req.session.user, success: true });
}
);
And that's it! Your app now has a login system! (That was very easy!)
We recommend you declare your providers in a file (or multiple files if you have a lot of them), say authenticationProviders.js, like this:
export const GoogleAuth = new GoogleProvider(options, (refresh_token, access_token, profile) => {
const user = User.findOne({ externalServiceId: profile.id });
return user;
});
export const SmileyGoogleAuth = new GoogleProvider(options, (refresh_token, access_token, profile) => {
const user = User.findOne({ externalServiceId: profile.id });
user.username = user.username + ' :D';
return user;
});
export const FrownyGithubWithModifiedId = new GoogleProvider(options, (refresh_token, access_token, profile) => {
const user = User.findOne({ externalServiceId: profile.id });
user.username = user.username + ' :(';
user.id = `GITHUB-${user.id}`;
return user;
});
And just use them in your routes!
import { GoogleAuth, FrownyGithubWithModifiedId } from './authenticationProviders';
router.get(
'/auth/google',
gatekeeper.authenticateWithProvider(GoogleAuth),
(req, res) => {
return res.json({ user: req.session.user, success: true });
}
);
router.get(
'/auth/frowny/github',
gatekeeper.authenticateWithProvider(FrownyGithubWithModifiedId),
(req, res) => {
return res.json({ user: req.session.user, success: true });
}
)
How to access the user once it has logged in?
Once the user has been authenticated, it will be stored in req.session.user.
Protecting Routes
To protect a route you can call gatekeeper.protect and pass to it a failure handler that specifies what to do in case the user is not authenticated (if you don't provide a failure handler, gatekeeper will just return a 401 status code response). Let's see it in action:
Example #1
router.get(
'/superSecret',
gatekeeper.protect(),
// The route handler gets called only when the user is authenticated
(req, res, next) => {
res.send(`
Now that you are authenticated, here is my secret...
I like coding and math!
`);
}
);
Example #2
router.get('/protected', gatekeeper.protect((req, res, next) => {
return res.redirect('/auth/google');
}), (req, res) => {
res.send('The user', req.session.user.id, 'is authenticated!');
});
✔️ That's it! Now you application has a secure, easy-to-use, and flexible authentication system with Gatekeeper! 🔐
We now recommend you to visit our Providers page to learn to implement your favorite providers.