CSRF token using SPA

谁说我不能喝 提交于 2020-05-29 11:56:29

问题


I'm using Vue js for the SPA and Laravel for the backend. It all works fine but once a form has been submitted the crsf token obviously hasn't refreshed so when I go to then submit another form I get a TokenMismatchException.

I can't put the csrf token into the form as vue throws an error when it attempts to render as the form is a component within vue.

I can access the csrf token using vue's default common headers by searching for name=_token which will work on the first request but on any requests after Laravel will return a TokenMismatchException as the token has been used recently by the currently logged in user.

I need to figure out a way so that the token can be refreshed without having to refresh the page as then it wouldn't be an SPA.

Any help would be appreciated.

Thanks.


回答1:


Something funky is going on within your setup, possibly some configuration with Vue, as your second statement is a bit off:

I can access the csrf token using vue's default common headers by searching for name=_token which will work on the first request but on any requests after Laravel will return a TokenMismatchException as the token has been used recently by the currently logged in user.

The above just isn't the case, unless they have logged out and logged back in, otherwise you can continue to use the same token.

I'm building a couple of SPA's with Laravel as the backend at the moment, the only time I do an actual traditional form submission is during a log in or log out sequence (so a full page refresh). The rest of the time it's just the same page using the same token.




回答2:


You can create a local variable with the csrf token value and assign it to the window like so (In your main layout blade file):

<script>
window.AppSettings = {
    csrfToken: "{{ csrf_token() }}"
}
</script>

then in your axios/vue-resource request use it:

axios.post("/some/path", { my: data, _token: AppSettings.csrfToken })
  .then(response => {
      console.log(response.data);
  })

The other workaround (not recommended at all) is to disable it in your middleware

in app/Http/Middleware/VerifyCsrfToken.php

protected $except = [
    "your/path/to/ignore"
];

But I'll go with the first option.



来源:https://stackoverflow.com/questions/41817303/csrf-token-using-spa

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