What is the best way to send secure parameter in Ajax Request?
Can a hacker change the parameters of myFunc() ?
Yes he can.
If he can, How to prevent change value?
You can't prevent it but you can verify the parameters within server side code.
What is the best way to send secure parameter?
What you can do is you can use mcrypt_encrypt() function for encrypting your string or data and while receiving data you can use mcrypt-decrypt() function else you can use your other encoding ways of PHP
You can check PHP mcrypt - Complete encryption and decryption of data
How to send secure AJAX requests with PHP and jQuery
1. Check the ORIGIN header
As specified by OWASP, this is not enough but recommended :
Although it is trivial to spoof any header from your own browser, it is generally impossible to do so in a CSRF attack, except via an XSS vulnerability. That's why checking headers is a reasonable first step in your CSRF defense, but since they aren't always present, its generally not considered a sufficient defense on its own.
And by Mozilla :
The Origin header is considered helpful against JSON data theft and CSRF attacks. The information provided by Origin--a bit of contextual request-creation information--should provide hints to web servers about trustworthiness of requests [...]
Checking the HTTP_ORIGIN
header could be written as :
header('Content-Type: application/json');
if (isset($_SERVER['HTTP_ORIGIN'])) {
$address = 'http://' . $_SERVER['SERVER_NAME'];
if (strpos($address, $_SERVER['HTTP_ORIGIN']) !== 0) {
exit(json_encode([
'error' => 'Invalid Origin header: ' . $_SERVER['HTTP_ORIGIN']
]));
}
} else {
exit(json_encode(['error' => 'No Origin header']));
}
1. (bis) Check the REFERER header
Again from OWASP :
If the Origin header is not present, verify the hostname in the Referer header matches the site's origin. Checking the referer is a commonly used method of preventing CSRF on embedded network devices because it does not require a per-user state.. This method of CSRF mitigation is also commonly used with unauthenticated requests [...]
Checking the HTTP_REFERER
is also quite simple in PHP with $_SERVER['HTTP_REFERER']
, you can just update the above code with it.
BE CAREFUL with the checking which always need to be really specific : do no check just example.com or api.example.com but the full https://example.com. Why ? Because you could spoof this check with an origin like api.example.com.hacker.com.
2. Generate CSRF tokens
A well-explained answer specific to PHP has been given there, in short :
Generate the token :
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}Add it in your generated views via a meta (like Github) :
<meta name="csrf-token" content="<?= $_SESSION['csrf_token'] ?>">
Setup jQuery ajax calls to include this token :
$.ajaxSetup({
headers : {
'CsrfToken': $('meta[name="csrf-token"]').attr('content')
}
});Server-side check your AJAX requests :
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
header('Content-Type: application/json');
$headers = apache_request_headers();
if (isset($headers['CsrfToken'])) {
if ($headers['CsrfToken'] !== $_SESSION['csrf_token']) {
exit(json_encode(['error' => 'Wrong CSRF token.']));
}
} else {
exit(json_encode(['error' => 'No CSRF token.']));
}
Most PHP frameworks have their own CSRF implementation, which more or less lay upon the same principle.
3. Sanitize validate user input.
You always must filter espace inputs and validate them.
4. Protect your server
- Limit the number of your requests.
- Use https as much as possible.
- Block bad queries.
- Protect POST requests.
5. Never trust user input
As @blue112 said, it is one of the most elementary security principles.
Secure ajax GET/POST request for server
I guess you are concerned about CSRF attacks. Read more about this here: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet
One of the mostly used option to secure your request will be:
- Generate a token and send it with the request for a session. This token can be identified by your WebServer as originating from a specific client for a specific session
How to pass parameters in $ajax POST?
I would recommend you to make use of the $.post
or $.get
syntax of jQuery for simple cases:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
});
If you need to catch the fail cases, just do this:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
Additionally, if you always send a JSON string, you can use $.getJSON or $.post with one more parameter at the very end.
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}, 'json');
Which is he most secure method of passing values to Ajax
There isn't much you can do to secure your front-end form. You can add all kinds of validation, but users can disable javascript, modify the form attributes in the DOM, etc. What you should do is validate the data on your server, and make sure it looks reasonable before you do anything serious with it.
There's also the issue of network security, like Greg mentioned in a comment above, but I don't know as much about that.
EDIT: If you don't want people snooping on the request in-flight, be sure to serve your site over https.
Related Topics
How to Call a Function When Element Is Loaded At Angular
How to Escape an Ampersand in a JavaScript String So That the Page Will Validate Strict
How to Capture the Browser Window Close Event
Automatically Refreshing Page Every 60 Seconds Using JavaScript
How to Remember the Value of a Variable After Reloading the Page
How to Pass Arguments to Addeventlistener Listener Function
Disable Scrolling When Touch Moving Certain Element
Check If Value Select2 Is Null
Can We Insert JavaScript into Any Webpage Loaded in the Browser
How to Remove a File from the Filelist
Convert an Object With Multiple Values Per Key into Array of Objects in Js
How to Translate the Following Jquery Code to React
Bootstrap Datepicker Appearing At Incorrect Location in a Modal
How to Append Whole Set of Model to Formdata and Obtain It in MVC
Select Drop Down Text-Align Center in Safari