简体   繁体   中英

How to get CSRF token from AdonisJs in VueJs?

I work on a project with an API made with AdonisJS and a front end made with VueJS.

The API and the front are independant and the front consumes the API with axios calls.

I'm trying to make a POST request with axios from the front, but the request sends a 403 response because of the missing csrf token.

In a "classic" Adonis project with Edge template, I know how to get the csrf token with {{ csrfField() }} . But how can I achieve this in this case where the front is independant from the API ?

I tried to make a route /csrf that sends the token from the session :

async csrf ({response, session}) { return response.json({token: session.get('csrf-secret')}) }

Then in Vue, I made a first axios call to get the token from this route, and then, pass the token to a second axios post call.

But this solution does'nt work (I think because it's not the same session, and so, not the same token) and by the way, i found this method not very clean.

So, does anyone have an idea of how to do this ?

I don't know adonis, but since adonis is similar to Laravel , you can do it their way. On Laravel there are route files for web and api. Web requires csrf_token while API won't, so basically you will put your routes on API but you won't have sessions etc. The other option is to make on the layout file that have the vuejs component a global window._csrf={{csrf_token()}} not sure how it is done on adonis. Then you will take it from the window object on vuejs. window._csrf

https://www.npmjs.com/package/universal-cookie universal cookies which is helps to set and get the value both server and client side

import Cookies from 'universal-cookie';
 
const cookies = new Cookies();
 
cookies.set('csrf', 'mytoken', { path: '/' });
console.log(cookies.get('csrf')); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM