Created
August 5, 2024 14:13
-
-
Save nsdevaraj/b8e0c26cbcaa1d56906e04f9945f8125 to your computer and use it in GitHub Desktop.
Prevention of Cross-Site Request Forgery (CSRF) Attacks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from 'express'; | |
import csrf from 'csurf'; | |
import cookieParser from 'cookie-parser'; | |
const app = express(); | |
app.use(cookieParser()); | |
app.use(csrf({ cookie: true })); | |
app.use((req, res, next) => { | |
res.locals.csrfToken = req.csrfToken(); | |
next(); | |
}); | |
app.post('/submit-form', (req, res) => { | |
// The CSRF token is automatically validated by the csurf middleware | |
// If validation fails, it will throw an error | |
// Process the form submission | |
res.send('Form submitted successfully'); | |
}); | |
// Error handler | |
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { | |
if (err.code === 'EBADCSRFTOKEN') { | |
res.status(403).send('CSRF token validation failed'); | |
} else { | |
next(err); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment