Reputation: 41
I am actually a backend developer but recently I became curious about nuxt3 and started developing a basic CRUD app. I created two separate apps for BE and FE for BE I used Go with Echo, but when I try to implement the CSRF token middleware to the BE it always started giving me the error. But when I use postman every thing works as it should be with no errors.
message "invalid csrf token"
I tried every solution I find using useFetch of vue and Axios didn't solve my problem.
on go side, I used default methods and didn't add a custom one
app.Use(middleware.CSRF())
Also defined CORS middleware
app.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{os.Getenv("APP_CLIENT_URL")},
AllowHeaders: []string{
echo.HeaderOrigin,
echo.HeaderContentType,
echo.HeaderAccept,
echo.HeaderAuthorization,
echo.HeaderXCSRFToken,
},
}))
And I am returning the generated csrf to the FR via a endpoint
func CsrfHandler(c echo.Context) error {
token := c.Get("csrf").(string)
return c.JSON(http.StatusOK, utils.Response(
true,
"CSRF token generated successfully",
models.Token{
Token: token,
ExpiresAt: "",
}))
}
After here I can display token on the FE side but for some reason getting 403 code.
On nuxt3 side for getting csrf-token
export const useCsrf = () => {
const csrfToken = ref('')
const config = useRuntimeConfig()
async function fetchCsrfToken() {
await useFetch('/csrf-token', {
baseURL: config.public.baseUrl,
method: 'GET',
onResponse({ response}): Promise<void> | void {
csrfToken.value = response._data.data.token
},
onRequestError({ error }) {
console.log('request error', error)
},
},
)
}
onMounted(fetchCsrfToken)
return {
csrfToken,
}
}
this is the method I use for creating user
const createUser = async (user: UserInterface, csrfToken: string) => {
await useFetch('/api/create-user', {
baseURL: config.public.baseUrl,
method: 'POST',
body: user,
onRequest({ options }) {
options.headers = {
'X-CSRF-Token': csrfToken,
'Authorization': `Bearer ${localStorage.getItem('api_key')}`
}
},
onRequestError({ error }) {
console.log('request error', error)
}
})
}
On postman I display a Cookie header but as I know since Set-Cookie parameter for http only I cant reach it and it is a security issue. So I don't know what to do.
Thanks for your help.
Upvotes: 0
Views: 1036