Sailsjs + vuejs + axios + CSRF tokens

半城伤御伤魂 提交于 2019-12-11 19:31:30

问题


i some thing not understand. Always get an error 403. I have a code in frontend(vue.js), here I get a token _csrf from Sails.js, its ok.

axios.get('http://localhost:1337/csrfToken')
        .then(response => {

            this.$store.commit('csrf_update', response.data._csrf);
            console.log("_csrf===",response.data._csrf);
            axios.defaults.headers.post['X-CSRF-Token'] = response.data._csrf;
        })

And i have a backend sails.js, settings in security.js

cors: {
 allRoutes: true,
 allowOrigins: 'http://localhost:8080',
 allowCredentials: false,
 allowRequestMethods:'GET, POST',
 allowRequestHeaders:'content-type, X-CSRF-Token'}, csrf: true

i have a token like that _csrf: lM8avM1X-KvKz9v2zLnbQZFf8lKOThX9Llb4 And i have error 403 when request.

axios.post('http://localhost:1337/login', form)
    .then(response => {
        this.$router.push('/kabinet');
    }).catch(error => { console.log(error); });

list 403

thats my Headers

headers

what's wrong?


回答1:


So, everything was very simple. In the (sails.js) file security.js to change allowCredentials: false on allowCredentials: true, and in frontend (vue.js) change axion, add parameter withCredentials: true like this

axios.get('http://localhost:1337/csrfToken',{ 
withCredentials: true
}).then(response => {
            console.log("_csrf===",response.data._csrf);
            axios.defaults.headers.post['X-CSRF-Token'] = response.data._csrf;
})

and in all axios requests must be withCredentials: true




回答2:


Sails has a property called csrf in the config>security file. If you set it on true you can simply add

<input type="hidden" name="_csrf" value="<%= _csrf %> />

to your form or at the place where you need it.

I am on sails 1.0.2 and it works quiet good.



来源:https://stackoverflow.com/questions/53173015/sailsjs-vuejs-axios-csrf-tokens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!