I have a login form that I am considering if it should be 'ajax'ed or not.
The reason I am contemplating this is because if the response of the ajax call is fixed (like 0 for invalid and 1 for valid) I can redirect the ajax request through the javascript console and log into the system maliciously.
Is there a way to solve this security issue?
Is that why all login forms I've seen so far (including here on stackoverflow) are non-ajax?
views:
42answers:
2You need to make sure that all content which should be displayed only to logged-in users should only be transferred after the login process. The server-side should check on every request whether the user is logged in or not. This could be done by traditional methods (like session ids in cookie or post/get).
So in short: don't transfer fixed values but transfer a normal session id which vary from user to user.
You perform your login with ajax.
Server side validates the login and starts a session.
Even if the client ignores the response from the ajax call, it's important that any ajax calls check if the session was properly created when login, and refuse to do what's asked if the session wasn't properly opened at login time.
In PHP (example):
Login:
<?php
header('Content-type: text/json');
session_start();
if ( check_password() ) {
// send ok response
}
else {
// send not ok response
}
// if that session variable exists, then we logged in successfully
$_SESSION['user'] = $user;
other ajax calls :
<?php
header('Content-type: text/json');
session_start();
if ( ! isset($_SESSION['user'] )) {
// send not ok response
// on the client, this will redirect to the login page
exit;
}
$user=$_SESSION['user'];
... rest of the code here
For every ajax call, when the response arrives, you should first check if the response is ok -- up to you to determine how you want this represented.
As an example, a response might look in JSON like
- not logged :
{ "ok":"N","error":"not logged in"}
- logged :
{ "ok":"Y","data":[{"name":"xxxx","age":19},{"name":"yyy","age":91}]}
- or
{ "ok":"Y","data":"Some text"}
etc, etc...
If it's ok, you proceed to handle the response. If not, you can for example redirect to the login page.
Note that with PHP, every ajax call you make includes the session ID automatically (it's a cookie), so PHP knows which session is associated with a particular request.