This tutorial of Passport.js te guiará a través de los pasos para configurar una strategy de autenticación Node.js local using Redis. You will learn to create an authentication interface with Passport.js, donde los usuarios proporcionarán sus nombres de Username y contraseñas. A pesar de su complejidad, los mecanismos de autenticación se pueden implementar fácilmente en Node.js.
Technologies to use
Before we jump headfirst into our Passport.js authentication tutorial, let's take a look at the technologies we're going to use in this chapter.
What is Passport.js?
- Passport.js is an authentication middleware Node.js simple and discreet for Node.js
- Passport.js se puede colocar en cualquier aplicación Web based on Express.js.
- Passport is a middleware authentication for Node.js that we are going to use for session management.
What is Redis?
Redis es un almacén de estructura de datos en memoria de Open Source (con licencia BSD), utilizado como base de datos, cache y intermediario de mensajes.
Redis is designed to support different types of abstract data structures, such as strings, hashes, lists, sets, ordered sets with range queries, bitmaps, hyperlinks, and geospatial indexes with radio queries.
We will store the information of the session of our user in Redis, and not in the memory of the process. In this way our application will be much easier to scale.
The demo application that needs authentication
For demonstration purposes, let's build an application that does just the following:
- expose a login form,
- expose two protected pages:
- a profile page,
- secured notes
The structure of the project
We are going to use the following structure:
├── app | ├── authentication | ├── note | ├── user | ├── index.js | └── layout.hbs ├── config | └── index.js ├── index.js └── package.json
As you can see, we will organize the files and directories around the characteristics. We will have a user page, a notes page and some functions related to authentication.
The Node.js authentication flow
Our target es implementar el siguiente flujo de autenticación en nuestra aplicación utilizando Passport.js:
- User enters username and password
- The application checks if they match.
- If they match, send a header Set-Cookie to be used to authenticate other pages.
- Cuando el usuario visita páginas del mismo domain, the cookie configurada previamente se agregará a todas las solicitudes
- Authenticate restricted pages with this cookie.
To configure an authentication strategy like this in a Node.js application using Passport.js, follow these three steps:
Step 1: Express Configuration
Vamos a utilizar Express para el marco del server.
// file: app / index.js const express = require ('express') const passport = require ('passport') const session = require ('express-session') const RedisStore = require ('connect-redis') ( session) const app = express () app.use (session ({store: new RedisStore ({url: config.redisStore.url}), secret: config.redisStore.secret, resave: false, saveUninitialized: false})) app .use (passport.initialize ()) app.use (passport.session ())
What did we do here?
First of all, we require all the dependencies that session management needs. After that, we have created a new instance of the module express-session, which will store our sessions.
For the backup store, we are using Redis, but you can use any other, like MySQL or MongoDB.
Step 2: Setting up Passport.js for Node.js
Passport.js is a great example of a library that uses plugins. In this tutorial of passport.js, we are adding the module passport-local which enables easy integration of a simple local authentication strategy using usernames and passwords.
For the sake of simplicity, in this example, we are not using a second backing store, but only an in-memory user instance. In real life applications, findUser it would look up a user in a database.
// file: app / authenticate / init.js const passport = require ('passport') const bcrypt = require ('bcrypt') const LocalStrategy = require ('passport-local'). Strategy const user = {username: 'test -user ', passwordHash:' bcrypt-hashed-password ', id: 1} passport.use (new LocalStrategy ((username, password, done) => {findUser (username, (err, user) => {if (err) ) {return done (err)} // User not found if (! user) {return done (null, false)} // Always use hashed passwords and fixed-time comparisons bcrypt.compare (password, user.passwordHash, (err , isValid) => {if (err) {return done (err)} if (! isValid) {return done (null, false)} return done (null, user)})})}))
Once the returns of findUser with our user object all that's left is to compare the user's hash password and the actual password to see if there is a match. Always store hashed passwords and use fixed time comparison to avoid time attacks.
If it's a match, we allow the user to enter: return done (null, user) (returning the user the Passport), if not we return an unauthorized error (returning nothing to the Passport- return done (null)).
Step 3: Add protected endpoints
To add protected endpoints, we are leveraging the pattern of middleware what do you use Express. For that, we are going to create the middleware authentication first:
// file: app / authentication / middleware.js function authenticationMiddleware () {return function (req, res, next) {if (req.isAuthenticated ()) {return next ()} res.redirect ('/')}}
It only has a role if the user is authenticated (has the correct cookies); just call the next middleware. Otherwise, it redirects to the page where the user can log in.
Its use is as easy as adding a new middleware to the route definition.
// file: app / user / init.js const passport = require ('passport') app.get ('/ profile', passport.authenticationMiddleware (), renderProfile)
Summary - Authentication with Passport.js
In this Passport.js tutorial, you have learned how to add basic authentication to your Node.js application. Later, you can extend it with different authentication strategies, such as Facebook or Twitter. You can find more strategies at http://passportjs.org/.