I've been googling for a while now, but still cannot get working CSURF CSRF protection between my NestJS app and my Nuxt SSR frontend.
Currently I have this implementation in my Nest main.js:
app.use(cookieParser());
app.use(csurf({ cookie: true }));
app.use((req, res, next) => {
const token = req.csrfToken();
res.cookie('XSRF-TOKEN', token);
next();
});
I'm not sure this is te correct way but I found this solution so far. The token
variable is changing every request. In my understanding req.cookie
sets this token to a cookie named XSRF-TOKEN
which should be available at my client.
In my Nuxt application I created a plugin:
export default function ({ $axios, $cookies }) {
$axios.onRequest(() => {
const token = $cookies.get('XSRF-TOKEN')
$axios.defaults.headers.common['x-xsrf-token'] = token
})
}
There are two behaviour here:
- The
token
is get from the cookie but once this is happen it stay the same for all requets - of course I getinvalid csrf token
error - The other case is when the
token
isundefined
.
My question is how can be implemented a secure csrf protection between this libraries?
Additional info:
$cookies
is from library cookie-universal-nuxt
lib
and I also set withCredentials: true
on axios calls:
await this.$axios.patch(`endpoint`, {}, { withCredentials: true })