I try to implement CSRF Attack in My webapplication,its implemented using codeigniter framework, this framework already have a options for protect CSRF attack. My issue issue i dont have a idea how to avoid CSRF attack in Ajax Call. Anyone have a idea please help me.
Thanks
You can do the following in your code, though my process may not be correct.
In the config.php set $config['csrf_protection'] = TRUE;
In every POST form if not using form helper, then before the submit button use the following hidden input:
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
Where Ajax is involved use code like -
..........
"ajax":{
url:"<?=site_url();?>folder/controllername/methodname",
type:"POST",
"dataType" : "json",
"data":{
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
},
},
...............
Related
sorry if I am missing something simple here. I am using CakePHP 3 and the Friendsofcake Search plug-in and trying to load my results with AJAX. I am not sure what to set for the URL - my understanding is the FormHelper url and the AJAX url must match for SecurityComponent. However even with that disabled I cannot get the form to submit. Any help is appreciated. The plugin is working fine otherwise and I can submit other forms using AJAX just fine - I suspect I am missing something here (or it's not possible - I am a beginning programmer)
<?php
$formUrl='//'.$_SERVER['HTTP_HOST'].Router::url(['controller'=>'Treasures','action'=>'frontIndex']);
echo $this->Form->create('Treasure',['id'=>'myForm','url'=>$formUrl]);
echo $this->Form->input('q');
... (Form submit, end, etc.)
?>
<script>
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
$.ajax({
async:true,
data:$(this).serialize(),
dataType:"html",
success:function (data, textStatus) {
$(".ajax-result").html(data);
},
type:"POST",
url:"<?=$formUrl?>"
});
</script>
<div class="ajax-result"></div>
Can someone tell me what I should be setting for the $formUrl? Currently the Controller action I am using this on successfully filters data with the search plugin and I have specialized the view to return AJAX results when requested - but there is obviously something else going on I am missing.
This works if I leave the URL blank and use GET instead of POST - should've thought of that sooner.
echo $this->Form->create('Treasure',['id'=>'myForm']);
...
?>
<script>
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
$.ajax({
async:true,
data:$(this).serialize(),
dataType:"html",
success:function (data, textStatus) {
$(".ajax-result").html(data);
},
type:"GET"
});
</script>
Works as expected. Hope this helps someone!
I'm learning to use the Phoenix framework, and I'm trying to do an AJAX post to a controller action - however, I'm running into a problem with the CSRF protection.
For starters, I'm not using a form - just want to pass text from an input to the controller:
<input type="text" id="raw-input" />
<button id="send-button">Send it!</button>
<script>
$("#send-button").click(function(){
var input = $("#raw-input").val();
$.ajax({
url: "/test/process",
type: "POST",
dataType: "json",
beforeSend: function(xhr) {xhr.setRequestHeader("X-CSRF-Token", $("meta[name='csrf-token']").attr("content"))},
data: {"input" : input},
success: function(response){
console.log(response);
}
});
});
</script>
The controller (not worried about doing anything input yet... just want to verify a successful post!):
def process(conn, %{"input" => input}) do
IO.puts "got it!"
end
And the router:
post "/test/process", TestController, :process
I pretty much lifted the $.ajax call from a Rails app where it was working fine, but it's not doing the trick here - running this returns a 403 error and logs (Plug.CSRFProtection.InvalidCSRFTokenError) invalid CSRF (Cross Site Request Forgery) token, make sure all requests include a valid '_csrf_token' param or 'x-csrf-token' header.
Can anyone offer any guidance? Thank you!
This is because Phoenix does not create a meta tag with the CSRF token by default. They're only included in forms generated by Phoenix's helper functions, and they're in a hidden input.
To get a CSRF token programatically in Phoenix, you can call Plug.CSRFProtection.get_csrf_token/0. There are many ways to pass this to your JS. You can add a meta tag to your layout to include it in every page but that might not be very efficient since it'll be generated for all pages. You can also just store it in a JS variable in the views that you require them in:
<input type="text" id="raw-input" />
<button id="send-button">Send it!</button>
<script>
$("#send-button").click(function(){
var CSRF_TOKEN = <%= raw Poison.encode!(Plug.CSRFProtection.get_csrf_token()) %>;
var input = $("#raw-input").val();
$.ajax({
url: "/test/process",
type: "POST",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", CSRF_TOKEN);
},
data: {"input" : input},
success: function(response){
console.log(response);
}
});
});
</script>
Phoenix already has helper csrf_meta_tag. Include it in the layout like so:
<html lang="en">
<head>
<%= csrf_meta_tag %>
...
And then use it in your js like so: $("meta[name='csrf-token']").attr("content")
If you want to skip the CSRF token check (in case you are developing APIs only) then you can comment out below line -
plug :protect_from_forgery
inside your respective _web/router.ex
The ajax call is established successfully. But when i try to get some response from the php there is a problem. In the .php file i have, <?php echo 'hello'; ?>. When i alert the parameter in the success function, it gives me the entire php file. The datatype requested in the ajax call is "text". Please let me know where i am making a mistake..
Code:
<script>
$(document).ready(function()
{
/* Attach a submit handler to the form */
//$("#foo").submit(function(event) {
$('form').on('submit', function(event){
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "ajaxSamplephp.php",
type: "post",
data: values,
datatype: "text",
success: function(data){
alert("success");
$("#result").html('Submitted successfully');
alert(data);
},
error:function(){
alert("failure");
$("#result").html('There is error while submit');
}
});
});
});
</script>
<body>
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<div id="result">RESULT</div>
</body>
PHP File
<?php
echo 'Hi I am some random';
?>
OUTPUT: <?echo 'Hi I am some random'; ?> in alert window
GOT THE OUTPUT: My URL was the problem. I use wamp server and Eclipse PDT. The workspace was there in a different location so i coulnt get the output.
And in php file i have given echo json_encode('[{"key":"value"}]'); In the ajax call, i have changed the data type to 'json'. But alerting like alert(data.key); gives me 'undefined' - message. Help would be greatly appreciated...
UPDATE (to answer second part of question): Do JSON.parse(data) to generate a JavaScript object from your JSON. Then you can use the object returned by the method to get the properties.
I'd check to see that your web server is configured to use PHP.
This could mean you have to install the PHP package (using something like sudo apt-get install php5) or enable PHP in your web server's configuration (I believe the libapache2-mod-php5 package on Ubuntu configures it for you).
I am creating a chat application using Node.js, and would like to have a file upload feature. While I can get the file uploaded, the browser would always be redirected to another link or page refreshed, and this of course disrupts the chat.
First I tried using Express to do it:
index.html:
<form id="fileSendButton" action="/" method="post" enctype="multipart/form-data">
<input type="text" name="title"><br>
<input type="file" name="upload" multiple="multiple"><br>
<input type="submit" value="Upload">
</form>
app.js:
app.post('/', function(req, res){
//some validation and rename file
res.send();
return false;
});
Next I tried using AJAX, but still couldnt do it, whenever the AJAX POST to the Node.js server, it would reload the page. My AJAX code anyway:
index.html:
$.ajax({
type: "POST",
url: "/",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("chatText").innerHTML = res;
}
});
return false;
Third I went to look at Uploadify, but didnt want to add Flash dependancy to my site, so I didnt implement it.
Anyone can help me please? I dont want a page reload when a file is uploaded.
You can do it with a dynamically created hidden frame on the client side.
see here for a detailed howto with expressjs.
Uploadify now has a pure HTML5 play.
I tried to use jQuery's ajax, but there is problem with cross domain requests(Canvas apps in Facebook are in iframe, and my browser Chrome, doesn't allow for making ajax requests to another domain (not facebook.com)).
Deprecated FBJS had Ajax proxy, but it is now deprecated.
How to deal with it?
Thanks for help.
If you use iframes, then making an AJAX call works. The iframe will be your own domain so it won't be a cross-domain request.
Actually you have to add cross domain requests in header.
I have done it in PHP.
JavaScript:-
Just have a look at it.
function ajax(id){
$.ajax({
type: "POST",
url: "json.php",
data: {id: id},
dataType : 'json',
forceIframeTransport: true, //force use iframe or will no work
success: function(result){
console.log(result);
},
error: function(errorThrown){
}
});
}
JSON.PHP:-
<?php
header('Access-Control-Allow-Origin: *');
$id = $_POST['id'];
$id = "test".$id;
$json = json_encode($id);
echo $json ;
?>
HTML CODE:-
<a onclick="ajax(3); return false;" id="result">Hello</a>