PassportJS (Patrick) - pmvdbijl7/matching-app GitHub Wiki

PassportJS

What is it?

Passport is authentication middleware for NodeJS. It is designed to serve a singular purpose: authenticate requests. When writing modules, encapsulation is a virtue, so Passport delegates all other functionality to the application. This separation of concerns keeps code clean and maintainable, and makes Passport extremely easy to integrate into an application.

Why should you use PassportJS?

Passport recognizes that each application has unique authentication requirements. Authentication mechanisms, known as strategies, are packaged as individual modules. Applications can choose which strategies to employ, without creating unnecessary dependencies.
Also, in modern web applications, authentication can take a variety of forms. Traditionally, users log in by providing a username and password. With the rise of social networking, single sign-on using an OAuth provider such as Google or Facebook has become a popular authentication method. Services that expose an API often require token-based credentials to protect access.

How to use?

To use Passport in your project you must first install it in your dependencies. To do that you just have to type npm install passport in your terminal. As mentioned earlier, with Passport you can also use a login method using an OAuth provider such as Google or Facebook. In my case, I chose to use Google as most applications use Google as a login method. For this you also need to install a seperate package in your dependencies:

$ npm install passport-google-oauth

Google OAuth 2.0

The Google OAuth 2.0 authentication strategy authenticates users using a Google account and OAuth 2.0 tokens. The strategy requires a verify callback, which accepts these credentials and calls done providing a user, as well as options specifying a client ID, client secret, and callback URL.
To enable the Google strategy in your application use the following code:

const passport = require('passport');
const GoogleStrategy = require('passport-google-auth').OAuth2Strategy;

passport.use(new GoogleStrategy({
    clientID: GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: 'https://localhost:3000/google/callback'
},
(accessToken, refreshToken, profile, done) => {
    User.findOrCreate({ googleId: profile.id }, (err, user) => {
        return done(err, user);
    })
}))

As you can see, you need to specify a Google clientID, clientSecret and callbackURL for the strategy to work. You can do this in your Google Developer Console. To request the details of the selected Google account, you need to add scopes to your "OAuth consent screen". In this case I retrieved the profile and email information.

Then you create a new credential and specify an authorized redirect URI. From this credential you get a clientID and a clientSecret which you can implement in your Google strategy code to make it work.

Finally, when you succesfully made your Google strategy, you have to specify routes to use this strategy. Use passport.authenticate(), specifying the 'google' strategy, to authenticate requests. Authentication with Google requires an extra scope parameter (which we set earlier in our Google Developer Console).

// Get the Google Authentication Page
app.get('/google',
    passport.authenticate('google', { scope: ['profile', 'email'] }));

// Get the Callback
app.get('/google/callback',
    passport.authenticate('google', { failureRedirect: '/login' }),
    (req, res) => {
        res.redirect('/');
    })

As you can see above, we specify a failureRedirect parameter so when, for some reason, the authentication goes wrong, the user get's redirected back to the login page.

Resources