Improved JWT security

This commit is contained in:
LukeGus
2025-09-26 23:27:07 -05:00
parent 2cd1cb64a3
commit b0f25a6971
17 changed files with 407 additions and 217 deletions

View File

@@ -207,17 +207,39 @@ class AuthManager {
});
}
/**
* Helper function to get secure cookie options based on request
*/
getSecureCookieOptions(req: any, maxAge: number = 24 * 60 * 60 * 1000) {
return {
httpOnly: true, // Prevent XSS attacks
secure: req.secure || req.headers['x-forwarded-proto'] === 'https', // Detect HTTPS properly
sameSite: "strict" as const, // Prevent CSRF attacks
maxAge: maxAge, // Session duration in milliseconds
path: "/", // Available site-wide
};
}
/**
* Authentication middleware
*/
createAuthMiddleware() {
return async (req: Request, res: Response, next: NextFunction) => {
const authHeader = req.headers["authorization"];
if (!authHeader?.startsWith("Bearer ")) {
return res.status(401).json({ error: "Missing Authorization header" });
// Try to get JWT from secure HttpOnly cookie first
let token = req.cookies?.jwt;
// Fallback to Authorization header for backward compatibility
if (!token) {
const authHeader = req.headers["authorization"];
if (authHeader?.startsWith("Bearer ")) {
token = authHeader.split(" ")[1];
}
}
if (!token) {
return res.status(401).json({ error: "Missing authentication token" });
}
const token = authHeader.split(" ")[1];
const payload = await this.verifyJWTToken(token);
if (!payload) {