I am getting CSRF Token mismatch error while I am updating my page. I have included csrf token in both input hidden fields and as well as in ajax call..still getting the same error.
Here is my input
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
And i have included in my ajax call like this
var sendInfo = {
'edit_qtype_id':edit_qtype_id,
'arr':arr,
'saveEditQtypeFile':1,
'qtype_name':qtype_name,
'qtype_subject_id':qtype_subject_id,
'qtype_topic_id':qtype_topic_id,
'qtype_option':qtype_option,
'_token' : $('#token').val()
};
Still getting CSRF Token mismatch.
Add the csrf in your blade like this
<meta name="csrf-token" content="{{ csrf_token() }}">
And then write this line above your AJAX call or at the start of your JS file.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
And finally remove the token from the ajax calls and try.
remove this line '_token' : $('#token').val().
Related
Hi all I am having a problem when trying to split this code into a js file from the laravel page: php
In laravel page
$(".importer").click(function(e) {
// Stops the form from reloading
var parent = $('#parentdoc').val();
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
}
});
let fichiers_upload = new FormData();
let TotalFichiers = $('#fichiers-upload')[0].files.length; //Total Images
let images = $('#fichiers-upload')[0];
for (let i = 0; i < TotalFichiers; i++) {
fichiers_upload.append('images' + i, images.files[i]);
}
fichiers_upload.append('TotalFichiers', TotalFichiers);
fichiers_upload.append('idf', parent);
$.ajax({
url: "{{route('upload')}}",
type: 'POST',
contentType: false,
processData: false,
data: fichiers_upload,
success: function(result) {
$('#fichiers-upload').val("");
}
});
});
This works fine in the laravel page but if I create a js page to separate it from the laravel page
doing
<link rel="stylesheet" href="{{ asset('admin/import.js')}}">
I get this error
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "/home/vol1_3/epizy.com/epiz_27528825/htdocs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
line: 369
message: "CSRF token mismatch." ```
First, the tag is wrong. This is for linking CSS:
<link rel="stylesheet" href="{{ asset('admin/import.js')}}">
What you want is a script element:
<script type="text/javascript" src="{{ asset('admin/import.js')}}"></script>
(I'm honestly surprised that even worked for you at all.)
More to the point of the error though, the literal string "{{ csrf_token() }}" is not the CSRF token. This is a placeholder which the server-side framework will replace with an actual value when rendering the page. But it doesn't do this for .js resources.
One approach could be to add that value to the page itself, perhaps somewhere in the <head> element:
<script type="text/javascript">
const csrf_token = "{{ csrf_token() }}";
</script>
As long as it's added before any other .js files are loaded, the window-level constant csrf_token would then be available to any of the other JavaScript code. Which you'd use in your AJAX:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': csrf_token
}
});
Alternatively, if you want you can just put the call to $.ajaxSetup itself in the page, after loading jQuery but before any of your AJAX calls, and then it can directly make use of the CSRF token placeholder. Either way works, it's a matter of personal preference.
Use Script tag instead of link tag to include your JS file:
<script src="{{ asset('admin/import.js')}}"></script>
Link tag is used to attach CSS files.
Try changing the token name to _token
headers: {
'_token': "{{ csrf_token() }}"
}
change :
<link rel="stylesheet" href="{{ asset('admin/import.js')}}">
to :
<script src="{{ asset('admin/import.js')}}"></script>
I made a Spring Boot Rest api to save users nic, username and password in a mySQL database. Used the tomcat 8096 port for that. Then I made a seperate project to make a registration form (JSP) to call the api I made earlier. When I run it and press the button, I got this error in the console ;
Access to XMLHttpRequest at 'http://localhost:8092/api/leavecal/saveuser' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is the code I used in my JSP
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1"/>
<title>Demo Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<center>
<div>
NIC No. : <input type="text" name="userNic" id="userNic"/>
</div>
Username : <input type="text" name="username" id="username"/>
<div>
Password : <input type="text" name="password" id="password"/>
</div>
<div>
<input type="submit" name="saveNewEmployee" id="saveNewEmployee" value="POST DATA" onclick="postDataFromAPI();"/>
</div>
</center>
<script>
function postDataFromAPI() {
var modelObj = {
userNic: $("#userNic").val(),
username: $("#username").val(),
password: $("#password").val()
};
console.log("post data:"+modelObj);
$.ajax({
type: "POST",
url: "http://localhost:8092/api/leavecal/saveuser",
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify(modelObj),
success: function (data) {
console.log("POST API RESPONSE::"+data);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
</script>
</body>
</html>
Any help is appreciated
Use
#CrossOrigin
annotation on top of your controller class.
I am having trouble with an AJAX POST request in Laravel. when access my site first time, it's get older CSRF token from cache.
When i reload the site again, its get correct token. How can i solve this?
Put your token that way to ajax request:
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
Or set token in header:
<meta name="csrf-token" content="{{ csrf_token() }}" />
and then:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
Good luck!
The csrf_token() changes when I use web middleware on the api routes.
api.php
Route::get('someroute/test', 'somecontroller')->middleware('web');
The controller
return response()->json([
'sent' => $request->header('token'),
'actual' => csrf_token()
]);
The token header comes from a meta tag that contains the csrf_token()
<meta id="csrf-token" content="{{ csrf_token() }}">
for some reason the token posted on the meta tag is different from the token on the server when I call the csrf_token() on the contoller.
Why is this crazy thing happening?
I have the following code:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="_csrf" th:content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
<title>Fileupload Test</title>
</head>
<body>
<p th:text="${msg}"></p>
<form action="#" th:action="#{/fileUpload}" method="post" enctype="multipart/form-data">
<input type="file" name="myFile"/>
<input type="submit"/>
</form>
</body>
</html>
I get the error HTTP 403:
Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'
CSRF is working if I use this line instead:
<form action="#" th:action="#{/fileUpload} + '?' + ${_csrf.parameterName} + '=' + ${_csrf.token}" method="post" enctype="multipart/form-data">
But how can I achieve working CSRF if I use headers?
After fighting with this issue for some time, I finally figured out why the code in the official Spring documentation doesn't work... Notice the following:
<meta name="_csrf" content="${_csrf.token}" />
<meta name="_csrf_header" content="${_csrf.headerName}" />
This is documentation with JSP in mind! Since we are using Thymeleaf, what you need to do is to use th:content instead of content:
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
Now it works!
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head>
<meta name="_csrf" th:content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
and
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$.ajax({
url: url,
method: 'DELETE',
success: function(result) {
$('#table').bootstrapTable('remove', {
field: 'id',
values: [row.id]
});
},
error:function(result) {
console.log(result);
}
});
Solved a problem with jquery ajax request delete .I use Spring Boot , Security and bootstrap -table .
Personally using same configuration as you (Thymleaf, Spring MVC, Spring Sec) i only was able to utilise meta csrf when uploading via ajax and direct inserts into action URL if submitting in standard fashion.
So different types of forms used:
e.g.
<form action="#" th:action="#{/fileUpload} + '?' + ${_csrf.parameterName} + '=' + ${_csrf.token}" method="post" enctype="multipart/form-data">
for Standard submition
<form action="#" th:action="#{/fileUpload}" method="post" enctype="multipart/form-data">
with following javascript:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
to submit via Ajax/jQuery.
Based on my recent research there doesn't seem to be a clean integration between the two and requires slight modifications to make code work.