Replies: 2 comments
-
How did you solve this? I've fixed it by using |
Beta Was this translation helpful? Give feedback.
0 replies
-
For anyone using import { CSRF } from 'remix-utils/csrf/server'
import { createCookie } from 'react-router'
import { CSRF_ERROR_MESSAGES } from '~/constants/general'
export const csrf_cookie = createCookie('csrf', {
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
secrets: [
process.env.CSRF_SECRET ||
'YOUR_BACKUP_SECRET_HERE',
],
})
export const csrf = new CSRF({
cookie: csrf_cookie,
formDataKey: 'csrf_token',
secret:
process.env.CSRF_SECRET ||
'YOUR_BACKUP_SECRET_HERE',
})
export const useCSRFValidation = () => {
/**
* Validates CSRF token from a request against the expected token stored in the cookie
*
* @param request The incoming request containing form data and cookies
* @param options Configuration options for error messages
* @returns The form data if validation passes, or error object if it fails
*/
async function validate(
request: Request,
options = {
token_error_message: CSRF_ERROR_MESSAGES.TOKEN_ERROR_MESSAGE,
form_error_message: CSRF_ERROR_MESSAGES.FORM_ERROR_MESSAGE,
},
) {
try {
const request_clone = request.clone()
const form_data = await request_clone.formData()
const submitted_token = form_data.get('csrf_token') as string | null
if (!submitted_token) {
throw new Error('CSRF token missing')
}
const expected_token = await csrf.getToken(request.headers)
let submitted_token_str = String(submitted_token).trim()
const expected_token_str = String(expected_token).trim()
if (
submitted_token_str.startsWith('"') &&
submitted_token_str.endsWith('"')
) {
submitted_token_str = submitted_token_str.slice(1, -1)
}
if (submitted_token_str !== expected_token_str) {
throw new Error('CSRF token mismatch')
}
return null
} catch (error) {
return {
errors: {
csrf_token: {
message: options.token_error_message,
},
},
form_error: options.form_error_message,
is_csrf_error: true,
}
}
}
return { validate }
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi there,
just spent couple of hours on trying to resolve some weird behaviour when using react-hook-form with csrf feature of remix-utils. It seems that
useForm
from react-hook-form is returning data enclosed with double quotes ("). So when usingcsrf.validate(request)
it fails on this line:because the
cookie
string is without double qoutes andformData.get(this.formDataKey)
is with double quotes...example:So it might be good to strip leading and trailing double quotes if they are present is csrf token string....
Beta Was this translation helpful? Give feedback.
All reactions