I am trying to get Relay and GraphQL set up with my Laravel server. I have successfully set Laravel up to serve GraphQL.
In the past, to make ajax calls with jQuery I added the following to my master.blade.php:
<meta name="csrf-token" content="{{ csrf_token() }}">
and the following to my main.js file:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
My GraphQL endpoint is currently returning token mismatch exception. It seems to me that Relay needs to pass the csrf-token to the server in a similar manner as jQuery.ajax. Where does it go?
Configure your network layer to append headers to each request:
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('/graphql', {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
})
);
The second argument to Relay.DefaultNetworkLayer gets passed through to the init argument of fetch(input, init). See the Relay Network Layer Guide for more information.
Related
I am building my first Laravel application and have a problem with the ajax request and specifically the CSRF verification.
I have followed all the steps in the documentation but it is not exactly doing what is said in there.
The App\Http\Middleware\VerifyCsrfToken middleware, which is included in the web middleware group by default, will automatically verify that the token in the request input matches the token stored in the session.
I have been manually concatenating 'test' to all CSRF tokens from the meta tag and the responses is still going through which it shouldn't of course.
Do I now have to manually Verify the CSRF token? If not what's the best practice to verify a token send in the headers of a jquery ajax post request through the controller?
I don't really understand what error that you encountered, but here's some Ajax setup and callin that i usually do.
//Setup header before callin ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//Ajax call update
$.ajax({
url: '/posts/1/update',
type: 'POST',
data: {
id: 123,
content: 'Abc123',
},
complete: function (response, xhr, settings) {
//Do something
}
});
You don't need to edit your VerifyCsrfToken middleware to make this work.
I am working with laravel. I want to save a post as accepted on click using ajax.
I am sending post using a href tag.
I don't want to use form for this.
here how I am sending post id to ajax
Accept
Here is my js function
function acceptProject($id) {
var projectId;
$.ajax({
alert(projectId);
});
}
but it is showing unexpected token in the console. This is very first week that I am writing ajax code so any mistake please consider.
You need to add X-CSRF-TOKEN token to your ajax request. Add the following code to your main layout, and continue making your ajax calls normally.
In header
<meta name="csrf-token" content="{{ csrf_token() }}" />
In script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
I'm using Laravel 5.2 for my web application and I have a page with multiple ajax requests by the same event. In $.ajax, I set async: true, Sometimes it shows CSRF token Mismatch error and redirect to login page. However when I set Async: false in ajax, it works fine but it takes lots of time.
Please help me so that it does not show token mismatch error.
in your form create one hidden filed name _token you can use this helper method to generate field
{!! csrf_field() !!}
in javascript you have to fetch this field value
var token = $( "input[name='_token']" ).val();
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston",_token:token }
});
another way create hidden a span or div add data attribute to it
<div id="token" data-token="{{ csrf_token() }}"></div>
fetch in javascript data value
var token = $( "#token" ).data('token');
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston",_token:token }
});
You said you use
$.ajaxSetup({ headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') } });
Maybe somewhere headers in request overrides, try to change it on
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name=_token]').attr('content') );
}
});
Please modify your url variable like so :
url: '/my-route'+'?_token=' + '{{ csrf_token() }}',
I think it is not possible to cater this scenario (handing concurrent async requests) in session based CSRF implementation.
Consider 2 async request, r1 and r2:
both are sync and hit at the same time for same session on the CSRF Filter.
r1 changes the CSRF token value which is stored for session id and completes its implementation.
whereas r2 gets TOKEN_MISMATCH since, it has the same old token in the request header which is now get expired by r1 request completion.
So, for r2, CSRF filter will raise error.
I am using responsive File Manager in my project. i need to add CSRF token in its config file that is inside public folder. using csrf_token() in that config file doesn't work:
$token = csrf_token(); //this is inside filemanager confing.php
Fatal error: Call to undefined function csrf_token() in
E:\xampp\htdoc\site\public\plugin\filemanager\config\config.php on line 7
so how can i access this function in public folder?or totally access app instance out of Laravel typical pathes?
Maybe try to turn off csrf protection for that route, or add this code to header of page where that editor is enabled:
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
}
});
});
</script>
I am developing a Laravel 5-BackboneJs Application. I'm using RESTful Resource controllers to make my own api.
I've got a Backbone model then I am calling save model method. It makes an ajax request like this:
gerencia.app/es/customrole/1
That's why I am trying tu update the model with id 1.
Backbone creates a request with PUT method:
But it gives me 500 internal server error! I see the preview then:
This is a TokenMismatchException from Laravel, then I've found I've got to send a token so I did this in my blade view:
<meta name="token" content="{{ Session::token() }}">
Then I've create a function to set the token and add this function to ajax beforeSend method:
function sendAuth( request ){
console.log( request );
return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content'));
}
model.save({
beforeSend: sendAuth,
success: function(){
console.log( 'success!' );
},
error: function(){
console.log( 'error!' );
}
});
But it doesn't work in spite of I see the token in request headers :(
Any help?
I was able to get this working by following the instructions on the Laravel site. I added this to my global layout file:
<meta name="csrf-token" content="{{ csrf_token() }}" />
Then, I created a JS file called csrf-token.js, and placed this code in it:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
After doing that, the POST requests from Backbone worked correctly and I can see the extra header in the request. The key for me was to include the csrf-token.js file AFTER Backbone:
<script src="{{ asset('js/lib/backbone-min.js') }}"></script>
<script src="{{ asset('js/csrf-token.js') }}"></script>
I guess Backbone overwrites the ajax setup options when it loads, so you need to include your changes after that.
My solution is to add a new key/value called token in my model method:
model.save({
"_token" : $("meta[name='token']").attr('content'),
success: function(){
console.log( 'success!' );
},
error: function(){
console.log( 'error!' );
}
});
You can post another solution to this issue.