Don’t forget your Passport! (not a travel guide)

Source: https://depositphotos.com/stock-photos/passport.html

To be able to travel and enter into a country, you need to show your passport with your credentials to be identified, then you can pass through and visit that country, similarly with passport.js, you are restricted to enter a route until you enter in the right credentials or sign up for it and now, you are granted access to visit the members page.

Passport is a package that does the work for you to authenticate users with a variety of strategies you can implement to your Express-based application such as using a username and password (local strategy), custom strategy, or even a single sign-on like Facebook, Spotify, Netflix, Twitter, GitHub, Google, and many more. For any Connect or Express-based application, you are required to initialize passport.js with this line “app.use(passport.initialize());”.

It is fairly simple that it can be easily integrated into your application and the most popular strategy used is the local strategy (install passport-local) for authenticating users with a username/email and password. By default, the usernameField is username but you can specify the type to be email. To specify which strategy you would like to use, you can call the passport.authenticate() and include the name of your strategy as the argument in your authenticate function and when authenticating the user is successful you can redirect them to the home page or the page you would like to send them to and you can also redirect them back to the login or sign up page if authenticating the request fails.

As I mentioned earlier, when the authentication is successful, the user can be redirected into a page you would like to redirect them to, and you can establish a session and store that into a cookie in the user’s browser. With cookies, they are made to be unique and it is used to identify that session and to be able to support these sessions, passport will serialize and deserialize user instances to and from the session.

Another thing this package includes is what you call “Flash Messages” which you can send an error message to the user like “Invalid email or password” or you could also flash a success message to the user as well. To be able to do this, you would need to require a req.flash() function (install connect-flash package if you are using Express 3.x.).

There are a number of things you could do with utilizing passport.js in your application and it depends what you would like to do with it. You could look into the documentation and read up more on their strategies in the links provided below. And as I mentioned, it is simple to use, easy to integrate and widely-used in web applications nowadays so check it out! Happy coding!

SOURCES:

http://www.passportjs.org/docs/

http://www.passportjs.org/docs/username-password/

A UC Berkeley Coding Bootcamp student from San Francisco, California.