Add Auth Middleware
Implement an auth middleware for protecting any sensitive APIs.
Now that your login and logout workflows are functional, let's add a middleware to protect your Express server's Session endpoint any other protected APIs in your backend.
Create Auth Middleware
To verify that frontend requests to your Session endpoint have an authenticated session, you can add an auth middleware that checks for a valid session cookie. Here's an example middleware function (e.g. src/middleware/auth-middleware.ts
):
// 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;
Protect the Session Endpoint
We can now stick the auth middleware in front of your Session endpoint that you created in previous steps.
Since the Session endpoint will now be protected by middleware, we can also remove the redundant session validation check in the controller code.
// app.ts
import { authMiddleware } from './middleware';
...
// Session endpoint
app.get('/session', [authMiddleware], (req, res) => {
const { email, isAuthenticated } = req.session;
//
// You can additionally make other API calls to gather any other data you might want to
// return to your frontend.
//
return res.status(200).json({ isAuthenticated, email });
});
...
Put All Protected Routes Behind Middleware
Protect all authenticated routes - not just the Session endpoint - with the auth middleware. Add this middleware to any endpoint that requires an authenticated user session.
The Login, Callback, and Logout Express routes are meant to be accessed by unauthenticated users. Avoid sticking the middleware in front of those routes.
Now that your Express server is protected, let's handle 401 HTTP responses in the React frontend.
Updated 1 day ago