Now that our Notes application can save its data in a database, we can think about the next phase of making this a real application, namely authenticating our users.
It's so natural to log in to a website to use its services. We do it every day, and we even trust banking and investment organizations to secure our financial information through login procedures on a website. HTTP is a stateless protocol, and a web application cannot tell much about one HTTP request versus another. Because HTTP is stateless, HTTP requests do not natively know whether the user driving the web browser is logged in, the user's identity, or even whether the HTTP request was initiated by a human being.
The typical method for user authentication is to send a cookie to the browser containing a token to carry user identity. The cookie needs to contain data identifying the browser and whether that browser is logged in. The cookie will then be sent with every request, letting the application track which user account is associated with the browser.
With Express, the best way to do this is with the express-session middleware. It stores data as a cookie and looks for that data on every browser request. It is easy to configure, but is not a complete solution for user authentication. There are several add-on modules that handle user authentication, and some even support authenticating users against third-party websites, such as Facebook or Twitter.
One package appears to be leading the pack in user authentication – Passport (http://passportjs.org/). It supports a long list of services against which to authenticate, making it easy to develop a website that lets users sign up with credentials from another website, for example, Twitter. Another, express-authentication (https://www.npmjs.com/package/express-authentication), bills itself as the opinionated alternative to Passport.
We will use Passport to authenticate users against both a locally stored user credentials database and using OAuth2 to authenticate against a Twitter account. We'll also take this as an opportunity to explore REST-based microservice implementation with Node.js.
In this chapter, we'll discuss the following three aspects of this phase:
- Creating a microservice to store user profile/authentication data.
- User authentication with a locally stored password.
- Using OAuth2 to support authentication via third-party services. Specifically, we'll use Twitter as a third-party authentication service.
Let's get started!
The first thing to do is duplicate the code used for the previous chapter. For example, if you kept that code in chap07/notes, create a new directory, chap08/notes.