I am building a REST API in PHP to work with a JavaScript based app. All requests are handled as JSON and some requests require authentication.
An example request would be:
$.ajax({
type: 'GET',
url: 'http://domain.com/api/posts/recent.json',
headers: {
Authorization: 'X-TRUEREST ' + $.param({
username: 'johndoe',
password: '********'
})
},
success: function(response){
// Handle response here (includes auth errors too)
},
error: function(a,b,c) {
}
});
I have based the use of HTTP Authentication headers on the code in this plugin: https://github.com/kvz/cakephp-rest-plugin/blob/master/Controller/Component/RestComponent.php#L532
As you can see they take passed parameters with the header and then they are used to log a user into the system if they are not already. From what I can tell they expect the auth credentials to be passed WITH the request for data.
An example of this is (note not using CakePHP in my example app):
if ( $loggedIn ) { // logged in is true of false based on session existing
// Then return the JSON as normal
} else {
// Grab HEADERS INFO
$headers = $_SERVER['HTTP_AUTHORIZATION'];
$parts = explode(' ', $_SERVER['HTTP_AUTHORIZATION']);
// Then use the parts to find a user in the DB... and populate $user
if($user){
$this->Auth->login($user); // login the user with our authentication code
// Then return JSON as normal
} else {
print json_encode(array('auth'=>false))
}
}
A few questions that I have though:
Question 1: Why use the HTTP Authentication and headers? As as far as I can tell, they are not offering me anything unless I am using them incorrectly? Why not just pass the username and password in the data param of the JS?
Question 2: As stated earlier I have based my API design on the Cake plugin above, but from what I can see they ALWAYS pass the username and password with every request and then decide to use it or not if the user is logged in. Is this correct? To me, it seems more likely that authentication and requests for data should be handled separately. Otherwise I would have to store the username and password in my JavaScript somewhere so that I can send it with each request.
Which brings me to the next question...
Question 3: How do I know if a user is logged in? I could set a variable to true and then pass that as part of my JSON with every request, but can a session work with an external device?