I'm building a Next.js application and on one of the pages, I need to call one of the /api
routes.
Calling this API route carries out a state-changing operation, so it's important to make sure the call is not coming from an attacker trying to impersonate my user.
Take the following as an example:
fetch('/api/grantPermissions', {
headers: ...,
method: 'POST',
body: JSON.stringify({resource: 'someresourceid', permission: 'somepermission'})
})
I've noticed there aren't many solutions for protecting a Next.js API route from a CSRF attack, so what I was considering is the following:
- When the user logs in, a random 32 byte hex string is generated
- It is stored in the session object (using iron-session)
- Using getServerSideProps(), the string stored in the session is injected into the page that needs to make the fetch call
- When the fetch call is being made, the CSRF token is attached with the request (e.g. in the body or custom header)
- The
/api/grant
route then checks if the CSRF token provided is the same as the one in the session
Is this a secure way of preventing a CSRF attack using the Synchronizer Token Pattern? What vulnerabilities could this approach lead to?