Add CSRF Token Middleware to an Express Server to Mitigate CSRF

Share this video with your friends

Send Tweet

In this lesson, we'll learn what CSRF tokens are, and how they are used to defeat Cross Site Request Forgery vulnerabilities. Even though we've defeated CSRF through the use of SameSite cookies, adding CSRF tokens are an important "defense in depth" strategy to ensure that browsers that don't support SameSite cookies can still be protected against CSRF.

Damian  Walczak
Damian Walczak
~ 5 years ago

I think it would be good to explain why evil.com cannot obtain CSRF token with fetch requests and inject it (credentials: include, CORS etc.)

Pabba Anubharath
Pabba Anubharath
~ 5 years ago

Could someone please help me to resolve this query at StackOverflow relevant to the above video: https://stackoverflow.com/questions/61077399/csrf-implementation-in-a-mern-stack

GrigorPenev
GrigorPenev
~ 4 years ago

For some reason, I always get EBADCSRFTOKEN regardless of the page I make the request from. Every time req.csrfToken() returns a diffrent token than the one csurf() generates..

For example, in request.session I get this:

csrfSecret: '9dunLanJHHXECGoxcDB4RtR6'

but request.csrfToken() returns this i6v9i4wB-mq7kRuC5gZVtQEH37LqO-mDPaDU/

GrigorPenev
GrigorPenev
~ 4 years ago

I figured out what the problem was:

I had written - <input type="hidden" name="_csrf" value=${request.csrfToken()} /> Instead of - <input type="hidden" name="_csrf" value=${request.csrfToken()}>

Apperantly html input elements of type hidden should not be closed...