Authenticating Node.js Applications With Passport
In this tutorial, we will develop a Node.js application from scratch and use the popular authentication middleware Passport to take care of our authentication concerns.
Passport's documentation describes it as a "simple, unobtrusive authentication middleware for Node" and rightly so.
By providing itself as middleware, Passport does an excellent job at separating the other concerns of a web application from its authentication needs. It allows Passport to be easily configured into any Express-based web application, just like we configure other Express middleware such as logging, body-parsing, cookie-parsing, and session-handling.
This tutorial assumes a basic understanding of Node.js and the Express framework to keep the focus on authentication, although we do create a sample Express app from scratch. We'll secure the app by adding routes to it and authenticating some of those routes.
Authentication Strategies
Passport provides us with 500 authentication mechanisms to choose from. You can authenticate against a local or remote database instance or use the single sign-on using OAuth providers for Facebook, Twitter, Google, etc. to authenticate with your social media accounts.
But don't worry: you don't need to include any strategy that your application does not need. All these strategies are independent of each other and packaged as separate node modules which are not included by default when you install Passport's middleware: npm install express --save
You can also install the express-generator with the following code snippet:
serializeUser function is used to persist a user's data into the session after successful authentication, while a passport, and create a file init.js with the following code snippets:
var User = require('../models/user');<br><br>module.exports = function(passport){<br><br> // Passport needs to be able to serialize and deserialize users to support persistent login sessions<br> passport.serializeUser(function(user, done) {<br> console.log('serializing user: ', user);<br> done(null, user._id);<br> });<br><br> passport.deserializeUser(function(id, done) {<br> User.findById(id, function(err, user) {<br> console.log('deserializing user:',user);<br> done(err, user);<br> });<br> });<br>}<br>
Using Passport Strategies
We will now define Passport's strategies for handling login and signup. Each of them would be an instance of the Local Authentication Strategy of Passport and would be created using the npm i connect-flash.
Login Strategy
Create a login.js file in the bcryptjs by executing the command passport.use() function.
var bCrypt = require('bcrypt-nodejs');<br><br>module.exports = function(passport){<br> <br> passport.use('login', ...)<br> );<br> <br> var isValidPassword = function(user, password){<br> return bCrypt.compareSync(password, user.password);<br> } <br>}<br>
If you're feeling uneasy with the code snippets and prefer to see the complete code in action, feel free to browse the code here.
Registration Strategy
Now, we create a signup.js file in the views folder of our application, we should see .jade files. Jade is a templating engine, primarily used for server-side templating in Node.js. It's a powerful way of writing markup and rendering pages dynamically using Express. It gives a lot more flexibility compared to using a static HTML file. To learn more about Jade and how it works, you can check out the documentation.
Next, we create the following four views for our application:
- layout.jade contains the basic layout and styling information.
- index.jade contains the login page providing the login form and giving the option to create a new account.
- register.jade contains the registration form.
- home.jade says hello and shows the logged-in user's details.
doctype html<br>html<br> head<br> title= title<br> link(rel='stylesheet', href='/stylesheets/style.css')<br> link(rel='stylesheet', href='http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css')<br> body<br> block content<br>
In the index.jade file, we will include the following code snippets:
extends layout<br><br>block content<br> div.container<br> div.row<br> div.col-sm-6.col-md-4.col-md-offset-4<br> h1.text-center.login-title Sign in to our Passport app<br> div.account-wall<br> img(class='profile-img', src='https://lh5.googleusercontent.com/-b0-k99FZlyE/AAAAAAAAAAI/AAAAAAAAAAA/eu7opA4byxI/photo.jpg?sz=120')<br> form(class='form-signin', action='/login', method='POST')<br> input(type='text', name='username' class='form-control', placeholder='Email',required, autofocus)<br> input(type='password', name='password' class='form-control', placeholder='Password', required)<br> button(class='btn btn-lg btn-primary btn-block', type='submit') Sign in<br> span.clearfix<br> a(href='/signup', class='text-center new-account') Create an account<br> #message<br> if message<br> h1.text-center.error-message #{message}<br>
In the register.jade file, we'll include the following code snippets:
extends layout<br><br>block content<br> div.container<br> div.row<br> div.col-sm-6.col-md-4.col-md-offset-4<br> h1.text-center.login-title Registration Details<br> div.signup-wall<br> form(class='form-signin', action='/signup', method='POST')<br> input(type='text', name='username', class='form-control', placeholder='Username',required, autofocus)<br> input(type='password', name='password', class='form-control nomargin', placeholder='Password', required)<br> input(type='email', name='email', class='form-control', placeholder='Email',required)<br> input(type='text', name='firstName', class='form-control', placeholder='First Name',required)<br> input(type='text', name='lastName', class='form-control', placeholder='Last Name',required)<br> button(class='btn btn-lg btn-primary btn-block', type='submit') Register<br> span.clearfix<br> #message<br> if message<br> h1.text-center.error-message #{message}<br>
In the home.jade file, we'll include the following code snippets:
extends layout<br><br>block content<br> div.container<br> div.row<br> div.col-sm-6.col-md-4.col-md-offset-4<br> #user<br> h1.text-center.login-title Welcome #{user.firstName}. Check your details below:<br> div.signup-wall<br> ul.user-details<br> li Username ---> #{user.username}<br> li Email ---> #{user.email}<br> li First Name ---> #{user.firstName} <br> li Last Name ---> #{user.lastName}<br> a(href='/signout', class='text-center new-account') Sign Out<br>
Now the registration page looks like this:

The Login page looks like this:

And the details page looks like this:

Implementing Logout Functionality
Passport, being middleware, makes it possible to add certain properties and methods on request and response objects. Passport has a very handy request.logout()
method which invalidates the user session apart from other properties.
So it's easy to define a logout route:
/* Handle Logout */<br> router.get('/signout', function(req, res, next) {<br> req.logout(function(err) {<br> if (err) { return next(err); }<br> res.redirect('/')<br> })<br> });<br>
Protecting Routes
Passport also gives the ability to protect access to a route which is deemed unfit for an anonymous user. This means that if a user tries to access http://localhost:3000/home without authenticating in the application, they will be redirected to the home page.
/* GET Home Page */<br>router.get('/home', isAuthenticated, function(req, res){<br> res.render('home', { user: req.user });<br>});<br><br>// As with any middleware it is quintessential to call next()<br>// if the user is authenticated<br>var isAuthenticated = function (req, res, next) {<br> if (req.isAuthenticated())<br> return next();<br> res.redirect('/');<br>}<br>
Conclusion
Passport is not the only player in this arena when it comes to authenticating Node.js applications, but the modularity, flexibility, community support, and the fact that it's just middleware make Passport a great choice.
For a detailed comparison of Passport and Everyauth, here is an interesting and informative perspective from the developer of Passport himself.
You can find the full source code for the example in our GitHub repo.
If you want to see what else you can do with Node.js, check out the range of Node.js items on Envato Market, from a responsive AJAX contact form to a URL shortener, or even a database CRUD generator.
This post has been updated with contributions from Mary Okosun. Mary is a software developer based in Lagos, Nigeria, with expertise in Node.js, JavaScript, MySQL, and NoSQL technologies.
The above is the detailed content of Authenticating Node.js Applications With Passport. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
