Dom Hall
Dom Hall

Reputation: 53

How do I get the CSRF token from Flask-wtf without jinja?

All the docs and examples I can find insert the token using "{{ csrf_token() }}". I can't do this because I'm working inside Vue templates (Which don't get parsed by jinja)

My index.html file is parsed by Jinja so I suspect a solution may involve this but I don't know where to start.

Edit: If I put it in index.html with

 <p>{{ csrf_token() }} </p>

it appears as expected but I'm not sure how to get this into my forms/axios requests

Upvotes: 0

Views: 1240

Answers (1)

Attack68
Attack68

Reputation: 4767

You will have a basic jinja template that loads the page using Vue.

In my particular case this is how I do it:

For Dynamic Content:

index.html

{% block content %}
  <div id="vue-container" backend-data="{{ csrf_token() }}"></div>
  <script nonce="{{ csp_nonce() }}">
      $('#vue-container').data('backend_current_user', {{ current_user_data | tojson }});
  </script>
{% endblock %}

{% block scripts %}
  <script src="{{ asset_url_for('index.js') }}"></script>
{% endblock %}

(note two methods are used here; an element attribute and JQuery. Actually I use the JQuery method more frequently since it is more flexible with JSON data)

index.js

import Vue from 'vue'
import Index from '@/components/Index.vue'

new Vue({
  render: function (h) {
    return h(Index, {
      props: {
        backendData: this.$el.attributes.backendData.value,
        backendCurrentUser: $('#vue-container').data('backend_current_user'),
      }
    })
  }
}).$mount('#vue-container')

index.Vue

<script>
export default {
  name: 'Index',
  props: {
    'backendCurrentUser': Object,
    'backendData': String
  },
...

For Static Content:

Actually for the csrf token I just place it in a script high enough on the page to load first:

base.html or index.html headers

<script type=text/javascript nonce="{{ csp_nonce() }}">
   $CSRF_TOKEN = '{{ csrf_token() }}';
</script>

and then use this inside templates/mixins:

  methods: {
    ajax_: function (url, action, formData, cb) {
      // eslint-disable-next-line
      formData.csrf_token = $CSRF_TOKEN || null 

Upvotes: 1

Related Questions