joseamtalavera / lhm_inmo_app

0 stars 0 forks source link

test security #9

Closed joseamtalavera closed 4 hours ago

joseamtalavera commented 3 hours ago

Preventing Attacks:


1- PROTECT AGAINST XSS usin HELMET

const helmet = requiere ('helmet')

2- SANITIZE AND VALIDATE INPUTS ONE THE PUBLIC FORUM

3- PROTECTION AGAINST SQL INJECTION (Prepare Statements)

4- CSRF (cross site request forgery) PREVENTION

Given that all your routes are in authRoutes.js, you should apply the CSRF protection middleware directly within this file to the routes that require it. Then, you can export the router and use an error-handing middleware in your main application file (e.g., app.js) to catch any CSRF-related errors. Here's how you can go about it:

In the app.js

  1. CSRF Protection Middleware Initialization:

const csrfProtection = csrf(); app.use(csrfProtection);

This initializes the CSRF protection middleware. When a request is made, this middleware generates a CSRF token and attaches it to the request object.

  1. Attaching CSRF Token to Session:

app.use((req, res, next) => { req.session.csrfToken = req.csrfToken(); next(); });

This middleware function retrieves the CSRF token generated by the csrf middleware (req.csrfToken()) and stores it in the session (req.session.csrfToken).

  1. Set the error handeling

app.use((err, req, res, next) => { if (err.code === 'EBADCSRFTOKEN'){ console.error('Invalid CSRF token detected'); console.log('Cookies:', req.cookies); console.log('Headers:', req.headers); console.log('CSRF Token from Session:', req.session.csrfToken); console.log('CSRF Token from Header:', req.get('csrf-token')); res.status(403).send({message: 'CSRF token is invalid'}); } else { next(); } });

In the authRoutes.js

We set up the router with the endpoint to send the to the client-side router.get('/csrf-token', (req, res) => { res.json({ csrfToken: req.csrfToken() }); });

In the Login.js

  1. set the useEffect to get the token from the session and pass it to the header request

useEffect(() => { const fetchCsrfToken = async () => { const response = await fetch(${process.env.REACT_APP_API_URL}/api/csrf-token, { method: 'GET', credentials: 'include', }); const data = await response.json(); setCsrfToken(data.csrfToken); console.log('CSRF token:', data.csrfToken); }; fetchCsrfToken(); }, []);

  1. In the handleSubmit, we include the token in the header

const response = await fetch(${process.env.REACT_APP_API_URL}/api/login, { method: 'POST', headers: { 'Content-Type': 'application/json', 'CSRF-Token': csrfToken,
}, body: JSON.stringify({ email, password }), credentials: 'include', });

5 - PENETRATION TEST