Quantcast
Channel: Symfony forms returning CSRF token is invalid from AJAX requests - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by Bilal Zahid for Symfony forms returning CSRF token is invalid from AJAX requests

$
0
0

The CSRF token uses, in part, cookies. When you generate two CSRFs on one page and submit one of the forms, you're invalidating the cookie.

Without some extensions on the framework itself, I can only really see one way around this -- and it's rather roundabout:

What you could do is set up a controller that generates your app form.

At the initial page load, your controller will load the login form as well as the app form. Upon submitting the login form via AJAX, you'll also request ONLY the controller for the app form (which will also give the user a new cookie). With javascript, you could then extract the NEW csrf token from the new form and inject it into the original app form. Then, when you submit the app form, it should have a new, valid csrf token.

To illustrate:

Get app form and login form -> submit login via AJAX -> get app form via AJAX in background -> steal new app form's csrf token and inject it into first app form -> submit app form.

      $.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

add this to your header->>

<meta name="csrf-token" content="{{ csrf_token() }}">

Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>
<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596344.js" async> </script>