How to add csrf token in ExtJS ajax call? - ajax

In my application i have both JSP and JS using Ext JS 5.1. I need to apply spring csrf protection to my application.
In Jsp i was able to add it as below :
<body>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}">
</body>
But i am not sure how to do it in .js files? Do i have declare Meta tag for ext js too? I need to apply the csrf token to every ajax request.
Just to highlight, i have scanned many sites but did not got any proper explanation or working example. How to add csrf in ajax calls of Ext js .js file ?

I was able to do it as follows. Add below snippet to your app.js or Application.js of ext js application.
Ext.Ajax.on('beforerequest', function(conn, options) {
var x = document.getElementsByTagName("META");
var token = "";
var headerVal = "";
var i;
for (i = 0; i < x.length; i++) {
if (x[i].name == "_csrf") {
token = x[i].content;
} else if (x[i].name == "_csrf_header") {
headerVal = x[i].content;
}
}
Ext.Ajax.setDefaultHeaders({
headerVal: token
});
});
OR
Ext.Ajax.on('beforerequest', function(conn, options) {
var x = document.getElementsByTagName("META");
var token = "";
var headerVal = "";
var i;
for (i = 0; i < x.length; i++) {
if (x[i].name == "_csrf")
{
token = x[i].content;
}
}
// Ext.Ajax.defaultHeaders = Ext.apply(Ext.Ajax.defaultHeaders || {}, { headerVal : token });
Ext.Ajax.setDefaultHeaders({
'X-CSRF-TOKEN':token
});
});

Related

progressbar for uploading file in laravel

my code is for input
<input id="imgages" name="imgages" type="file" onchange="uploadFile()" />
and my script is :
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("imgages").files[0];
var formdata = new FormData();
formdata.append("imgages", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event) {
_("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}
function completeHandler(event) {
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0; //wil clear progress bar after successful upload
}
function errorHandler(event) {
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event) {
_("status").innerHTML = "Upload Aborted";
}
my problem is how can i chenge this part to use url for laravel and add csrf in this ajax part??
I mean I dont know how to add csrf token laravel in this script.
ajax.open("POST", "file_upload_parser.php");
You can add the csrf token in the head of your html ...
<meta name="csrf-token" content="{{ csrf_token() }}">
... and use formData.set('_token', document.querySelector('[name="csrf-token"]').getAttribute('content')) to send it with the request.
I found my problem
I have to add token after formdata.append("imgages", file);
formdata.append("imgages", file);
formdata.append("_token", '{{ csrf_token() }}');
and I add a route for store in host.

how can I solve csrf verification failed

I'm trying to create form that uploads a zip file to the server. But everytime I click the submit I keep getting CSRF verification failed error. This is my html code:
<form method="POST" name="form-import-file" enctype="multipart/form-data">
<div>
<input type="file" id="file" name="file" accept=".zip"/>
<input type="submit" value="Upload file">
</div>
</form>
<div class="url-csrf" data-csrf="{{ csrf_token }}"></div>
<div class="url-import-file" data-url-import-file="{% url 'intent:import_file' %}"></div>
In my .js code:
$("form[name='form-import-file']").submit(function(e) {
var formData = new FormData($(this)[0]);
alert(formData);
var json_data = {'csrfmiddlewaretoken' : $('.url-csrf').attr('data-csrf'), 'file': formData };
$.ajax({
url: $('.url-import-file').attr('data-url-import-file'),
type: "POST",
data: json_data,
success: function (msg) {
alert(msg)
},
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
});
{% csrf_token %} is hidden input field not a value
In Html
<div id="csrf_token">
{% csrf_token %}
</div>
In js
let csrfToken = $("#csrf_token").val();
var json_data = {'csrfmiddlewaretoken' : csrfToken, 'file': formData };
Did you try with the cookie based CSRF provided by django doc?
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
Then add 'csrfmiddlewaretoken' : csrftoken, in you json_data
The best approach is probably the one described in Django documentation: Cross Site Request Forgery protection
If your CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY settings are False, I suggest you create init.js file and always load it in your base html template. Include these two functions in this file:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};
To include CSRF token in your ajax requests, you include it in request headers with this code:
$(document).ready(function () {
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
});
You can include this in init.js file you created earlier, if you wish, but it must be loaded after jQuery library.
If you have CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY set to True, add {% csrf_token %} to your forms (or somewhere else in your HTML), read the token from there and include it in your ajax request, for example like this:
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
$.ajax({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
url: ...
...
...
});
A simple solution is to use ensure_csrf_cookie
in the view that renders the page. Important, the decorator must be in the view that renders the page,
not in the view that receives the post request.
from django.views.decorators.csrf import ensure_csrf_cookie
#ensure_csrf_cookie
def get_the_page(request):
return render(request, 'template.html')

How to load XML from an external site server (using AJAX)?

Here I have an example I'm building (with help).
Currently, the XML is stored in a data island. But what if I wanted to make a request to an external server? Would I use an XMLHttpRequest?
How would I code that in this example, and avoid the Cross Origin XMLHttpRequest problem?
In this example, I've tried playing with function loadXMLDoc(statelabel) but without success.
Am I on the right track with this function?
function loadXMLDoc( statelabel ) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "state_data.xml", true);
xhttp.send();
}
Fully functional code here:
<!DOCTYPE html>
<!--
SO
datalist / xml handling
Q 51200490 (https://stackoverflow.com/questions/51200490/how-to-find-the-node-position-of-a-value-in-an-xml-tree/51201494)
A
-->
<html>
<head>
<title>SO sample</title>
<script>
// Setup of keypress event handler, default selection of xml data.
function setupEH () {
var n = document.getElementById("myInputId");
n.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
loadXMLDoc('Alabama'); // comment out this line if you want a vanilla UI after loading the html page.
}
// Load the xml document
function loadXMLDoc( statelabel ) {
// The xml document is retrieved with the following steps:
// 1. Obtain the (in-document) source as a DOM node.
// 2. Extract textual content.
// 3. Instantiate the xml parser (a browser built-in)
// 4. Parse textual content into an xml document
//
// When retrieving the xml document by means of ajax, these steps will be handled by the library for you - a parsed xml document will be available as a property or through calling a method.
//
let x_xmlisland = document.getElementById("template_xml");
let s_xmlsource = x_xmlisland.textContent;
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(s_xmlsource, "application/xml");
myFunction(xmlDoc, statelabel); // Actual work ...
}
// Processing the xml document
function myFunction(xmlDoc, statelabel) {
// debugger; // uncomment to trace
//
// Every bit of information is processed as follows:
// - Get the relevant xml subtree ( `UNIT` element of the selected state incl.descendants )
// - Extract the textual value.
// - Feed the textual value to the Html elements prsenting the result.
//
var xpr_current_unit = xmlDoc.evaluate("/STATE_DATA/UNIT[./STATE[./text() = '"+statelabel+"']]",xmlDoc,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE,null);
var node_current_unit = xpr_current_unit.iterateNext();
//
// The subsequent calls to xmlDoc.evaluate set the current UNIT element as their context node ('starting point'/'temporary root' for the xpath expression).
// The context node is referenced by '.' (dot)
//
var xpr_s = xmlDoc.evaluate("./STATE/text()",node_current_unit,null,XPathResult.ORDERED_ANY_TYPE,null);
var node_s = xpr_s.iterateNext();
var s = node_s.textContent
document.getElementById("state").innerHTML = s;
var xpr_g = xmlDoc.evaluate("./GDP/text()",node_current_unit,null,XPathResult.ORDERED_ANY_TYPE,null);
var node_g = xpr_g.iterateNext();
var g = "Unknown";
if ( node_g !== null ) {
g = node_g.textContent;
}
document.getElementById("gdp").innerHTML = g;
var xpr_p = xmlDoc.evaluate("./POPULATION/text()",node_current_unit,null,XPathResult.ORDERED_ANY_TYPE,null);
var node_p = xpr_p.iterateNext();
var p = "Unknown";
if ( node_p !== null ) {
p = node_p.textContent;
}
document.getElementById("population").innerHTML = p;
// cf. https://stackoverflow.com/a/3437009
var xpr_u = xmlDoc.evaluate("count(./preceding::UNIT)+1.",node_current_unit,null,XPathResult.ORDERED_ANY_TYPE,null);
var n_ucount = xpr_u.numberValue;
document.getElementById("inputValue").innerHTML = s;
document.getElementById("nodePosition").innerHTML = n_ucount;
}
// Setup the submit click handler
function ehClick ( ) {
let node_choice = document.getElementById('myInputId');
loadXMLDoc(node_choice.value);
}
</script>
<style>
</style>
</head>
<body onload="setupEH()">
<script id="template_xml" type="text/xml"><?xml version="1.0" encoding="UTF-8"?>
<STATE_DATA>
<UNIT>
<STATE>Wisconsin</STATE>
<GDP>232,300,000,000</GDP>
<POPULATION>5,800,000</POPULATION>
</UNIT>
<UNIT>
<STATE>Alabama</STATE>
<GDP>165,800,000,000</GDP>
<POPULATION>4,900,000</POPULATION>
</UNIT>
<UNIT>
<STATE>California</STATE>
<!-- Note: the GDP node for this unit is missing -->
<POPULATION>39,600,000</POPULATION>
</UNIT>
<UNIT>
<STATE>Texas</STATE>
<GDP>1,600,000,000,000</GDP>
<POPULATION>28,300,000</POPULATION>
</UNIT>
<UNIT>
<STATE>Michigan</STATE>
<GDP>382,000,000</GDP>
<POPULATION>10,000,000</POPULATION>
</UNIT>
</STATE_DATA>
</script>
<input list="myInput" id="myInputId" value="">
<button id="myButton" onClick="ehClick()">submit</button>
<p>input value: <span id="inputValue"></span></p>
<p>XML tree node position of input value: <span id="nodePosition"></span></p>
<p>State: <span id="state"></span></p>
<p>GDP: <span id="gdp"></span></p>
<p>Population: <span id="population"></span></p>
<datalist id="myInput">
<option id="AL">Alabama</option>
<option id="CA">California</option>
<option id="MI">Michigan</option>
<option id="TX">Texas</option>
<option id="WI">Wisconsin</option>
</datalist>
</body>
</html>
This gets a little bit involved using vanilla XMLHttpRequest to load XML. Here is a quick sample.
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "sample.xml" , true);
xmlhttp.send();
}
function myFunction(xml) {
var x, i, xmlDoc, table;
xmlDoc = xml.responseXML;
table = "<tr><th>Artist</th><th>Title</th></tr>";
x = xmlDoc.getElementsByTagName("CD")
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
However, it gets much more complicated esp. if you want to do a cross-domain request.
That's probably the right moment to pick up jQuery to make things easier:
$.ajax({
url: 'https://www.w3schools.com/xml/note.xml',
dataType: 'XML',
type: 'GET',
async: false,
crossDomain: true,
success: function () { },$.ajax({
url: 'https://www.w3schools.com/xml/note.xml',
dataType: 'XML',
type: 'GET',
async: false,
crossDomain: true,
success: function () { },
failure: function () { },
complete: function (xml) {
// Parse the xml file and get data
var xmlDoc = $.parseXML(xml);
$xml = $(xmlDoc);
$xml.find('body').each(function () {
console.log($(this).text());
});
}
});

File uploading using ajax and servlets

I was trying to upload file in my web application using ajax and servlets.
My ajax code is something like this :
<script>
var client = new XMLHttpRequest();
function upload2() {
alert("in upload");
var file = document.getElementById("uploadfile");
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append("upload", file.files[0]);
client.open("post", "fileupload", true);
client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
}
/* Check the response status */
client.onreadystatechange = function () {
if (client.readyState == 4 && client.status == 200) {
alert(client.statusText);
}
}
</script>
My form is something like this :
<input type="file" name="uploadfile" id="uploadfile"/>
<input type="button" value="upload" name="upload" onclick="upload2()"/>
And my servlet that is being called in function is :
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
for (FileItem fi : upload.parseRequest(request)) {
if (fi.isFormField()) {
continue;
}
System.out.println("filename: " + fi.getName());
InputStream is = fi.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\Files\\" + fi.getName());
int x = is.read();
while (x >= 0) {
fos.write((byte) x);
x = is.read();
System.out.println("reading");
}
}
But am getting an exception with this code :
org.apache.commons.fileupload.FileUploadException: the request was
rejected because no multipart boundary was found
The main problem I think is how to use the form data that has been formed by appending the file in my Servlet part.
My question is what is the cause of this exception?
Second question is how to modify my code so that I can upload multiple files at a time? Please help.

AJAX works in IE but not in Firefox or Chrome

I'm new to using AJAX and my code works in Internet Explorer but not in Firefox or Chrome.
I do not know what it is exactly what should change in the code ...
// I think that error should be here :-)
function cerrar(div)
{
document.getElementById(div).style.display = 'none';
document.getElementById(div).innerHTML = '';
}
function get_ajax(url,capa,metodo){
var ajax=creaAjax();
var capaContenedora = document.getElementById(capa);
if (metodo.toUpperCase()=='GET'){
ajax.open ('GET', url, true);
ajax.onreadystatechange = function() {
if (ajax.readyState==1){
capaContenedora.innerHTML= "<center><img src=\"imagenes/down.gif\" /><br><font color='000000'><b>Cargando...</b></font></center>";
} else if (ajax.readyState==4){
if(ajax.status==200){
document.getElementById(capa).innerHTML=ajax.responseText;
}else if(ajax.status==404){
capaContenedora.innerHTML = "<CENTER><H2><B>ERROR 404</B></H2>EL ARTISTA NO ESTA</CENTER>";
} else {
capaContenedora.innerHTML = "Error: ".ajax.status;
}
} // ****
}
ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajax.send(null);
return
}
}
function creaAjax(){
var objetoAjax=false;
try{objetoAjax = new ActiveXObject("Msxml2.XMLHTTP");}
catch(e){try {objetoAjax = new ActiveXObject("Microsoft.XMLHTTP");}
catch (E){objetoAjax = false;}}
if(!objetoAjax && typeof XMLHttpRequest!='undefined') {
objetoAjax = new XMLHttpRequest();} return objetoAjax;
}
//These functions are connected with a form
function resultado(contenido){
var url='ajax/buscar.php?'+ contenido +'';// Vota Resultado
var capa='resultado';
var metodo='get';
get_ajax(url,capa,metodo);
}
function paginas(contenido){
var url='ajax/paginar.php?'+ contenido +'';// Vota Paginas
var capa='paginas';
var metodo='get';
get_ajax(url,capa,metodo);
}
Strongly suggest that you use a lib like jQuery that encapsulates a lot of what you're doing above, masking cross-browser issues (current and future). Even if you don't want to use jQuery site-wide, you could still use it just for its AJAX functionality.

Resources