Add Auth Middleware

Implement auth middleware to ensure only authenticated users access sensitive APIs.

Now that your application is properly managing sessions, let's add middleware to verify that only users with valid sessions can access protected backend APIs.


Create Auth Middleware

To verify that frontend requests to your Session endpoint have an authenticated session, you can create an auth middleware that checks for a valid session cookie. Below is an example of an auth middleware function:

// auth-middleware.ts

// Middleware to ensure an authenticated user session is present for the current request.
const authMiddleware = async function (req, res, next) {
  const { isAuthenticated } = req.session;
  if (!isAuthenticated) {
    return res.status(401).send();
  }

  // Save the session in order to "touch" it and extend the session expiration window.
  await req.session.save();
  return next();
};

export default authMiddleware;




Enable Auth Middleware For Session Endpoint

Now that we've created the auth middleware, we'll need to update our Session Endpoint definition so that the auth middleware gets executed before each request. Also, since the session cookie is being validated by the middleware now, we can remove the logic from the Session Endpoint that was checking to see if the user was authenticated. The Session Endpoint implementation should now look like the following example:

// app.ts
import { authMiddleware } from './middleware';

...

// Add authMiddleware to protect the Session Endpoint.
app.get('/session', [authMiddleware], (req, res) => {
  const { userId, tenantId } = req.session;
  
  //
  // This check can be removed since the session is now validated in
  // the auth middleware
  //  
  // if (!isAuthenticated) {
  //   return res.status(401).send();
  // }

  return res.status(200).json({ userId, tenantId });
});

...



Enable Auth Middleware For Your Application's Protected Endpoints

Make sure to add the auth middleware in front of any other endpoints in your application that require an authenticated user session. Below is an example showing how to protect your endpoints with the auth middleware.

import { authMiddleware } from './middleware';

app.get('/protected-api', [authMiddleware], (req, res) => {
  res.status(200).send("This is a protected endpoint");
});

📘

Does The Auth Middleware Need to be Applied to The Auth Endpoints?

The Login, Callback, and Logout Endpoints are meant to be accessed by unauthenticated users, so you don't need to add the auth middleware in front of them.


What’s Next

Now that your server endpoints are protected, let's update the frontend code to handle unauthorized error responses.