Learn Node.js · 9/13

Security: Authentication and Authorization

10 min read

Security: Authentication and Authorization 🛡️

Welcome, intrepid Node.js developer! It's time to put on our security hats and talk about a crucial aspect of any application: making sure the right people have access to the right things. We'll explore how to verify who our users are (Authentication) and what they're allowed to do (Authorization).

Think of your application as an exclusive club. Authentication is the bouncer at the door checking IDs to make sure only members get in. Authorization is the set of rules that determines which areas of the club a member can access – the general floor, the VIP lounge, or the super-secret "we-don't-talk-about-it" room.

Let's get this security party started!


1. Stateful vs. Stateless: Sessions vs. Tokens 🎟️

The Problem: Imagine a user logs into your application. They send their username and password, and you verify them. Great! But when they navigate to another page, how does your server know it's the same user? HTTP, the protocol of the web, is inherently "stateless," meaning each request is independent and the server doesn't remember previous interactions. It's like having a conversation with someone who has severe short-term memory loss – you'd have to reintroduce yourself every single time you speak. Annoying, right?

The Solution: We need a way for the server to remember a logged-in user across multiple requests. This is where stateful and stateless authentication mechanisms come into play.

Stateful Authentication (Sessions) 🍪

In a stateful system, after a user successfully logs in, the server creates a "session" for them and stores information about that session on the server-side (e.g., in memory or a database). The server then sends a unique session ID to the user's browser, which is stored as a cookie.

How it works:

  1. Login: User sends credentials (username/password).
  2. Verification: Server verifies the credentials.
  3. Session Creation: Server creates a session and stores it.
  4. Cookie Response: Server sends a response with a cookie containing the session ID.
  5. Subsequent Requests: For every subsequent request, the browser automatically sends the cookie with the session ID. The server then looks up this session ID in its storage to identify the user and their state.

It's like getting a wristband at a music festival. The first time you enter, they check your ticket (credentials). Then, they give you a wristband (session ID). For the rest of the festival, you just show your wristband to get back in. The festival organizers (server) have a record of all the valid wristbands.

Industry Practice: While simple to implement, server-side sessions can become difficult to manage at scale. If you have multiple servers, you need to ensure that sessions are synchronized across all of them, which can add complexity.

Stateless Authentication (Tokens) 🎫

With stateless authentication, the server does not store any session information. Instead, after a user logs in, the server generates a token that contains all the necessary information to identify the user. This token is then sent to the client.

How it works:

  1. Login: User sends credentials.
  2. Verification: Server verifies the credentials.
  3. Token Generation: Server generates a token (like a JWT) and signs it with a secret key.
  4. Token Response: Server sends the token back to the client.
  5. Subsequent Requests: The client stores this token (e.g., in localStorage or an HttpOnly cookie) and sends it in the Authorization header of every subsequent request. The server then verifies the token's signature to ensure it's valid and hasn't been tampered with.

This is like having a VIP pass for an event. The pass itself contains all the information needed to grant you access (your name, access level, etc.) and has a special seal (the signature) to prove it's authentic. The bouncers (server) don't need to check a master list; they just need to look at your pass and verify its authenticity.

Industry Practice: Token-based authentication, particularly with JSON Web Tokens (JWTs), is very popular in modern web applications, especially those with microservices architectures or separate front-end and back-end applications. It's scalable and decouples authentication from your server's storage.


2. Securing Passwords: Hashing with bcrypt 🔒

The Problem: You absolutely, positively, under no circumstances, should ever store user passwords in plain text in your database. If your database is ever compromised (and let's be real, it's a possibility), an attacker would have access to every user's password. That's a catastrophic security breach waiting to happen. It's the digital equivalent of writing all your secrets in a diary and leaving it on a park bench.

The Solution: We need to transform the passwords into a non-readable format before storing them. This process is called "hashing." A hash function takes an input (the password) and produces a fixed-size string of characters, which is the "hash." Crucially, this is a one-way process; you can't reverse-engineer the original password from the hash.

Enter bcrypt

bcrypt is a popular and highly secure password-hashing function. What makes bcrypt special is that it's intentionally slow. This might sound like a bad thing, but it's actually a feature! Its slowness makes it resistant to "brute-force attacks," where an attacker tries to guess passwords by hashing a huge list of common words and comparing them to the stored hashes.

Interesting Fact: bcrypt also includes a "salt" automatically. A salt is a random piece of data that is added to the password before hashing. This ensures that even if two users have the same password, their stored hashes will be different. This prevents "rainbow table" attacks, where attackers have pre-computed hashes for common passwords.

Getting Started with bcrypt

First, you'll need to install the bcrypt library.

bash
npm install bcrypt

Example: Hashing a Password

Here's how you can hash a password before saving it to your database.

javascript
const bcrypt = require('bcrypt');

async function hashPassword(password) {
  const saltRounds = 10; // The cost factor. Higher is more secure but slower.
  try {
    const salt = await bcrypt.genSalt(saltRounds);
    const hash = await bcrypt.hash(password, salt);
    return hash;
  } catch (error) {
    console.error('Error hashing password:', error);
  }
}

// Example usage:
hashPassword('mySuperSecretPassword123').then(hashedPassword => {
  console.log('Hashed Password:', hashedPassword);
  // Now you would store this hashedPassword in your database.
});

Example: Comparing a Password

When a user tries to log in, you'll need to compare the password they provided with the hash you have stored.

javascript
const bcrypt = require('bcrypt');

async function comparePassword(plainPassword, hashedPassword) {
  try {
    const isMatch = await bcrypt.compare(plainPassword, hashedPassword);
    return isMatch;
  } catch (error) {
    console.error('Error comparing password:', error);
  }
}

// Example usage (assuming you've fetched the hashedPassword from your DB):
const storedHash = '$2b$10$abcdefghijklmnopqrstuv'; // Example hash
comparePassword('mySuperSecretPassword123', storedHash).then(isMatch => {
  if (isMatch) {
    console.log('Password is correct! User can log in.');
  } else {
    console.log('Incorrect password.');
  }
});

3. Implementing JWT (JSON Web Tokens) for Logins 🚀

The Problem: Now that we understand stateless authentication, how do we actually create these magical tokens? We need a standardized, secure way to create tokens that can be trusted by our server.

The Solution: JSON Web Tokens (JWTs) are an open standard for creating tokens that assert some number of claims. A JWT is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

A JWT looks like this: xxxxx.yyyyy.zzzzz. It has three parts, separated by dots:

  1. Header: Contains information about the type of token and the signing algorithm used.
  2. Payload: Contains the "claims," which are statements about an entity (typically, the user) and additional data. You might include the user's ID, their role, etc.
  3. Signature: This is created by taking the encoded header, the encoded payload, a secret key, and signing it with the algorithm specified in the header. The signature is used to verify that the message wasn't changed along the way.

Getting Started with jsonwebtoken

The jsonwebtoken library is the most popular way to work with JWTs in Node.js.

bash
npm install jsonwebtoken

Example: Creating a JWT on Login

After a user successfully logs in (you've checked their password with bcrypt), you can generate a JWT for them.

javascript
const jwt = require('jsonwebtoken');

function createToken(user) {
  // The payload typically contains user information.
  const payload = {
    userId: user.id,
    username: user.username,
    // You can add other relevant data here.
  };

  // Your secret key should be stored securely, e.g., in an environment variable.
  const secret = process.env.JWT_SECRET;

  const options = {
    expiresIn: '1h', // Token will expire in 1 hour.
  };

  return jwt.sign(payload, secret, options);
}

// Example usage after successful login:
const user = { id: 123, username: 'testuser' };
const token = createToken(user);
console.log('Generated JWT:', token);
// Now you send this token back to the client.

Fun Fact: Your JWT secret is like the secret ingredient in your grandma's famous cookie recipe. If anyone else gets it, they can bake their own cookies (forge tokens) and pretend they're from her kitchen (your server). Guard it well!


4. Creating Auth Middleware to Protect Routes 🚦

The Problem: We've got our users logging in and receiving JWTs. But how do we actually restrict access to certain parts of our application? We need a way to check for a valid token on incoming requests to protected routes.

The Solution: Middleware functions in Express.js are perfect for this. Middleware are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. We can create a piece of middleware that checks for a valid JWT and either allows the request to proceed to the route handler or sends an error response.

Implementing Authentication Middleware

This middleware will typically do the following:

  1. Check for the token in the Authorization header. The standard format is Bearer <token>.
  2. If no token is found, send a "401 Unauthorized" response.
  3. If a token is found, verify it using your secret key.
  4. If the token is invalid or expired, send a "401 Unauthorized" response.
  5. If the token is valid, extract the payload (which contains user information), attach it to the request object (e.g., req.user), and call next() to pass control to the next function in the stack.

Example: Auth Middleware

javascript
const jwt = require('jsonwebtoken');

function authMiddleware(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer <token>

  if (token == null) {
    return res.sendStatus(401); // Unauthorized
  }

  jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
    if (err) {
      return res.sendStatus(403); // Forbidden
    }
    req.user = user;
    next();
  });
}

Using the Middleware to Protect a Route

Now, you can easily apply this middleware to any route you want to protect.

javascript
const express = require('express');
const app = express();
const authMiddleware = require('./authMiddleware'); // Assuming you saved the middleware in a separate file.

// This is a public route, accessible to everyone.
app.get('/api/public-data', (req, res) => {
  res.json({ message: 'This is public data.' });
});

// This is a protected route. The authMiddleware will run before the route handler.
app.get('/api/protected-data', authMiddleware, (req, res) => {
  // Because of the middleware, we can access the user's information from the token.
  res.json({ message: `Hello, ${req.user.username}! This is protected data.` });
});

app.listen(3000, () => console.log('Server is running on port 3000'));

And there you have it! You've built a solid foundation for securing your Node.js application. You can now confidently check IDs at the door and ensure only authorized users access your protected resources.


Further Reading and Resources 📚

Challenge

You are tasked with securing an Express.js application. Your goal is to implement a middleware function named authenticateToken.

This middleware must:

  1. Retrieve the Authorization header from the incoming request (req).
  2. Extract the JSON Web Token (JWT) from the header. The header format is expected to be Bearer <token>.
  3. If no token is present, immediately end the request-response cycle by sending a 401 Unauthorized status.
  4. If a token is present, verify it using the jsonwebtoken library's verify method. The secret key is stored in process.env.JWT_SECRET.
  5. If the token is invalid or expired, respond with a 403 Forbidden status.
  6. If the token is valid, attach the decoded user payload to req.user and pass control to the next middleware in the stack.

Complete the authenticateToken function in the provided code block.

Expected result

Your code should be a single JavaScript function named authenticateToken. This function must correctly perform the following actions:

  • Access the authorization header from the req.headers object.
  • Isolate the token string, which follows the "Bearer " prefix.
  • Use a conditional check to see if a token exists. If not, it should call res.sendStatus(401) and terminate the function.
  • Use the jwt.verify method with the token, the secret key from process.env.JWT_SECRET, and a callback function.
  • Inside the callback, it must check for an error. If an error exists, it should call res.sendStatus(403).
  • If there is no error, it should assign the decoded payload (the second argument of the callback, often named user) to req.user and then call the next() function to pass control to the next route handler.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.