The problem
So for a while now I've been experimenting with different AJAX approaches in sending data to a server that will be processed and stored inside a MySQL database.
The page that the AJAX request hits api.php
, uses PHP's PDO prepared statements to save the data, so MySQL injections aren't really a problem and the passwords or data that needs to be encrypted are also handled by api.php
which isn't what I'm asking here. My question relates more to how to ensure the data is secure when being transferred from the client to the server.
The approaches
I currently have (for the login example I have included below):
- SSL Cert/HTTPS running on the domain.
- Certain AJAX request (obviously not this login request example as there is no session to begin with) will only work if the PHP Session is valid across the site (used on both
login.php
and api.php
in this example).
- Rate limiting on
api.php
when accessing functions.
- PHP PDO prepared statements when interacting with the database inside
api.php
.
- Encrypts sensitive data inside
api.php
(not relevant to the question).
The questions
Finally, my questions are:
- Is this approach to using asynchronous HTTP (Ajax) requests safe enough to use rather than just submitting data to a PHP page and redirecting onwards? (As this way improves the user's experience).
- How can I check to know that the data my user's are sending hasn't been tampered with?
- Am I reasonably doing enough to protect my user's data, if not, what else can I do?
The example
I understand everyone has different approaches to handling their site's data and transporting that data. I also understand that no matter what you do, you can never be 100% protected, as there may be vulnerabilities and ways around your system that you can't account for. I'm looking for feedback/improvements on my general approach in sending data securely rather than criticism of the specific code below as it is only an example. But any constructive answers are welcome. Thanks for taking the time to read/answer.
function loginUser() {
var process = "loginUser";
var data = $("form").serializeArray();
data[1].value = SHA512(data[1].value); // sha then encrypt on api.php page
data = JSON.stringify(data);
$("#loginButton").html('<i class="fa fa-spinner fa-pulse fa-lg fa-fw"></i> Login');
$.ajax({
type: "POST",
url: "api.php",
data: {"process": process, "data": data},
success: function(data) {
if (data.response.state == "success") {
// if api.php returns success, redirect to homepage
} else {
// if api.php returns failure, display error
}
},
error: function(jqXHR, textStatus, errorThrown, data) {
// error handling
},
dataType: "json"
});
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…