- See also
CHAPTER 18. Security
Authentication
Passport
- Username & Password
git clone https://github.com/passport/todos-express-starter.git username-password-tutorial
Node.js Basics
-
Installing Node.js:
-
Download and install Node.js from [nodejs.org](https://nodejs.org/).
-
-
Checking Node.js Version:
-
Check the installed Node.js version:
node -v
-
-
npm (Node Package Manager):
-
Install packages:
npm install package-name
-
Initialize a new project:
npm init
-
-
Creating a Basic Server:
-
Create a simple HTTP server:
-
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
server.listen(3000, 'localhost', () => {
console.log('Server is running on http://localhost:3000/');
});
Modules
-
CommonJS Modules:
-
Node.js uses CommonJS module system.
-
Import modules:
const module = require('module-name')
-
Export modules:
module.exports = something
-
-
Built-in Modules:
-
Node.js provides a set of core modules like
fs
,http
, andpath
.
-
-
Creating and Using Custom Modules:
-
Create a module in a separate file and use
require
to import it.
-
File System Operations
-
fs (File System):
-
Read a file:
fs.readFile('file.txt', 'utf8', (err, data) ⇒ { /* … */ });
-
Write to a file:
fs.writeFile('file.txt', 'data', (err) ⇒ { /* … */ });
-
-
Path Module:
-
Handle file and directory paths:
const path = require('path');
-
Asynchronous Programming
-
Callbacks:
-
Use callbacks to handle asynchronous operations.
-
-
Promises:
-
Promises provide a cleaner way to handle async operations.
-
Create a Promise with
new Promise((resolve, reject) ⇒ { /* … */ });
-
-
Async/Await:
-
Modern way to handle async operations using
async
andawait
keywords.
-
Event Emitter
-
EventEmitter:
-
Core module for handling events in Node.js.
-
-
Custom Events:
-
Create and emit custom events using EventEmitter.
-
HTTP and Networking
-
http Module:
-
Create HTTP servers and clients.
-
Make HTTP requests using
http.get()
orhttp.request()
.
-
-
Express.js:
-
Popular web framework for building web applications and APIs.
-
Working with JSON
-
JSON Parsing:
-
Parse JSON:
JSON.parse(jsonString)
-
-
JSON Stringify:
-
Convert an object to JSON:
JSON.stringify(jsonObject)
-
Debugging
-
console.log():
-
Print messages to the console for debugging.
-
-
Node.js Debugger:
-
Debug Node.js applications using the built-in debugger.
-
Streams
-
Streams:
-
Efficiently process data in chunks, such as files or network data.
-
-
Readable Streams:
-
Read data from a source.
-
-
Writable Streams:
-
Write data to a destination.
-
Express.js Basics
-
Installing Express.js:
-
Install Express.js using npm:
npm install express
-
-
Creating an Express App:
-
Import and initialize Express:
const express = require('express');
-
Create an Express application:
const app = express();
-
-
Starting the Server:
-
Start the server on a specific port:
app.listen(3000, () ⇒ console.log('Server started on port 3000'));
-
-
Routing:
-
Define routes using HTTP verbs (
GET
,POST
,PUT
,DELETE
).
-
-
Middleware:
-
Use middleware functions for request processing.
-
Add middleware using
app.use()
.
-
-
Static Files:
-
Serve static files (e.g., CSS, images) using
express.static()
middleware.
-
Routing
-
Basic Routing:
-
Handle requests with
app.get()
,app.post()
, etc. -
Define route parameters with
:param
.
-
-
Route Parameters:
-
Access route parameters using
req.params
.
-
-
Route Handlers:
-
Define route-specific middleware using
app.use()
.
-
-
Middleware Functions:
-
Middleware functions have access to
req
(request) andres
(response) objects.
-
-
Error Handling:
-
Handle errors with
app.use()
middleware functions with four parameters (error handling middleware).
-
-
Redirects:
-
Redirect requests using
res.redirect()
.
-
Request and Response Objects
-
req (Request Object):
-
Contains information about the incoming request (e.g.,
req.params
,req.query
).
-
-
res (Response Object):
-
Used to send responses to the client.
-
-
Response Methods:
-
res.send()
: Send a response. -
res.json()
: Send JSON response. -
res.status()
: Set the HTTP status code. -
res.render()
: Render HTML templates.
-
Middleware
-
Custom Middleware:
-
Create custom middleware functions using
app.use()
.
-
-
Third-party Middleware:
-
Use third-party middleware for tasks like body parsing (
body-parser
) and authentication (passport
).
-
Templating Engines
-
Using Templating Engines:
-
Integrate templating engines like EJS or Pug using
app.set('view engine', 'engine-name')
.
-
-
Rendering Views:
-
Render views using
res.render()
.
-
RESTful APIs
-
RESTful Routes:
-
Design routes following RESTful principles (e.g.,
/api/users
,GET /api/users/:id
).
-
-
CRUD Operations:
-
Implement CRUD (Create, Read, Update, Delete) operations for resources.
-
-
JSON API:
-
Serve and consume JSON data for RESTful APIs.
-
Authentication and Authorization
-
Authentication:
-
Implement user authentication using middleware (e.g., Passport.js).
-
-
Authorization:
-
Control access to routes using authorization middleware.
-
Error Handling
-
Global Error Handler:
-
Create a global error handler to catch and handle errors.
-
-
HTTP Error Codes:
-
Use appropriate HTTP status codes (e.g., 404 for not found, 500 for server errors).
-
-
Logging Errors:
-
Log errors for debugging and monitoring.
-
Passport.js Basics
-
Installing Passport.js:
-
Install Passport.js using npm:
npm install passport
-
-
Setting Up Passport.js:
-
Import Passport.js and initialize it:
-
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
-
Authentication Strategies:
-
Passport.js supports various authentication strategies, including Local, OAuth, and more.
-
Local Authentication (Username/Password)
-
Local Strategy:
-
Authenticate users with a username and password.
-
Install
passport-local
strategy:npm install passport-local
-
-
Configuring the Local Strategy:
-
Configure Passport to use the Local Strategy:
-
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
(username, password, done) => {
// Find user in the database and verify credentials
// Call done() with user or false based on authentication
}
));
-
Serializing and Deserializing Users:
-
Serialize user to the session and deserialize user from the session:
-
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
// Retrieve user by ID from the database
done(null, user);
});
-
Authentication Routes:
-
Create routes for login, registration, and logout.
-
-
Middleware:
-
Protect routes by adding
passport.authenticate()
as middleware.
-
OAuth Authentication
-
OAuth Strategies:
-
Implement OAuth authentication with strategies like Google, Facebook, Twitter, etc.
-
Install passport-oauth strategy:
npm install passport-oauth
-
-
Configuring OAuth Strategies:
-
Configure Passport to use an OAuth strategy:
-
const OAuthStrategy = require('passport-oauth').OAuthStrategy;
passport.use(new OAuthStrategy(
{
// Strategy options
},
(token, tokenSecret, profile, done) => {
// Verify user and fetch profile
// Call done() with user or false based on authentication
}
));
-
OAuth Redirects:
-
Handle OAuth callback and redirect URLs.
-
-
Middleware:
-
Protect routes with
passport.authenticate()
for OAuth authentication.
-
Custom Authentication Strategies
-
Custom Strategies:
-
Implement custom authentication strategies by extending
passport.Strategy
.
-
-
Configuring Custom Strategies:
-
Configure and use custom strategies with Passport.js.
-
Sessions and Cookies
-
Sessions:
-
Passport.js manages user sessions.
-
Serialize and deserialize user objects to/from sessions.
-
-
Cookies:
-
Passport.js uses cookies to store session data.
-
User Authorization
-
User Roles and Permissions:
-
Implement user roles and permissions to control access to resources.
-
-
Authorization Middleware:
-
Create custom authorization middleware functions.
-
OAuth Basics
-
What is OAuth?:
-
OAuth (Open Authorization) is an open standard protocol for securing authorization and authentication between two parties, often referred to as the client and the resource owner (usually a user).
-
-
OAuth Roles:
-
Resource Owner: The user who grants access to their protected resources.
-
Client: The application requesting access to the protected resources.
-
Authorization Server: The server that authenticates the user and issues access tokens.
-
Resource Server: The server that hosts the protected resources.
-
-
OAuth Flows:
-
OAuth defines multiple flows, including:
-
Authorization Code Flow
-
Implicit Flow
-
Client Credentials Flow
-
Resource Owner Password Credentials Flow
-
-
Access Token:
-
An access token is a short-lived credential that authorizes the client to access specific resources on behalf of the user.
-
-
Refresh Token:
-
A refresh token is a long-lived credential used to obtain a new access token when it expires without requiring the user to log in again.
-
OAuth 2.0 Authorization Code Flow
-
Authorization Request:
-
The client initiates the flow by redirecting the user to the authorization server’s authorization endpoint.
-
Includes client ID, redirect URI, and scope.
-
-
User Authentication:
-
The user authenticates with the authorization server.
-
-
Authorization Grant:
-
After successful authentication, the authorization server redirects the user back to the client’s redirect URI with an authorization code.
-
-
Access Token Request:
-
The client exchanges the authorization code for an access token by making a POST request to the token endpoint.
-
Includes client credentials, authorization code, and redirect URI.
-
-
Access Token Response:
-
The authorization server responds with an access token and, optionally, a refresh token.
-
-
Accessing Protected Resources:
-
The client uses the access token to request and access protected resources from the resource server.
-
OAuth 2.0 Implicit Flow
-
Authorization Request:
-
Similar to the Authorization Code Flow but returns the access token directly in the URL fragment.
-
-
User Authentication:
-
The user authenticates with the authorization server.
-
-
Access Token Response:
-
The authorization server sends the access token as a URL fragment to the client’s redirect URI.
-
-
Accessing Protected Resources:
-
The client can immediately access protected resources using the access token.
-
OAuth 2.0 Client Credentials Flow
-
Access Token Request:
-
The client directly requests an access token from the authorization server by sending its client credentials (client ID and client secret).
-
-
Access Token Response:
-
The authorization server responds with an access token.
-
-
Accessing Protected Resources:
-
The client uses the access token to access protected resources from the resource server.
-
OAuth 2.0 Resource Owner Password Credentials Flow
-
Access Token Request:
-
The client requests an access token by sending the user’s credentials (username and password) to the authorization server.
-
-
Access Token Response:
-
The authorization server responds with an access token.
-
-
Accessing Protected Resources:
-
The client uses the access token to access protected resources from the resource server.
-
OAuth 2.0 Security Best Practices
-
Use HTTPS:
-
Always use HTTPS to secure communication between the client and the authorization server.
-
-
Client Authentication:
-
Protect client credentials, and consider using client authentication for all flows.
-
-
Token Expiration and Refresh:
-
Implement token expiration and refresh mechanisms to enhance security.
-
-
Scopes:
-
Limit the scope of access requested by the client to the minimum required for its functionality.
-
-
User Consent:
-
Ensure users provide informed consent before granting access to their data.
-
-
Token Revocation:
-
Implement token revocation to allow users to revoke access.
-
-
Token Storage:
-
Safely store tokens on the client-side, using best practices for securing tokens.
-