Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Csrf token in vue component

I have Laravel 5.3 project with Vue.js integrated and I want to use CSRF-TOKEN in my form. Form html code is in Vue component file in

resources / assets / js / bootstrap.js

I have this:

Vue.http.interceptors.push((request, next) => {
    request.headers.set('X-CSRF-TOKEN', MyApp.csrfToken);
    next();
});

then I have main vue file /resources/assets/js/app.js:

require('./bootstrap');
Vue.component('callbackwindow', require('./components/callbackwindow.vue'));

const app = new Vue({
    el: '#app',
    data: { },
});

then in Vue file I need to use csrf_field, but I don't know how to get it there, because standard php csrf_field() is not rendered inside Vue component and I don't know how to import MyApp.csrfToken.

<template>
<div class="modal fade" >
    <form @submit.prevent="submitForm" name="callback" method="POST" action="/" role="form" class="form-horizontal" enctype="multipart/form-data">
    {!! csrf_field() !!}
    ...form code here...
    </form>
</div>
</template>
<script>
    export default {    }
</script>

Is it possible to import MyApp.csrfToken variable from here into my Vue template file?

like image 207
schel4ok Avatar asked Dec 31 '16 16:12

schel4ok


People also ask

How do I add CSRF tokens?

CSRF tokens are secrets and should be handled as such in a secure manner throughout their lifecycle. Place the field containing the CSRF token as early as possible within the HTML file. Place the field that contains the token before any non-hidden fields and before any places where user-controllable data is embedded.

What is {% CSRF token %}?

What are CSRF tokens? A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client.


2 Answers

As an alternative ways:

1- Get the token from meta tag with csrf-token name inside of <head>:

$('meta[name="csrf-token"]').attr('content')

2- Pass it as a prop to your Vue component:

<your-component :csrf-token="{{ csrf_token() }}"></your-component>
like image 195
YaserKH Avatar answered Oct 27 '22 08:10

YaserKH


If you have written meta tags for csrf token in the master template then try this.

<template>
      <form action = "/user/checkout" method="POST">
        <input type="hidden" name="_token" v-bind:value="csrf">
       ....
      </form>
</template>

In the script tag of the component:

 <script>
    export default{

        data(){
          return {
            //csrf token
             csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
       }
    }

    </script>
like image 21
Murad Avatar answered Oct 27 '22 09:10

Murad