I'm building a PHP REST API that will be utilized from a JavaScript client, and am having some issues figuring out how to implement the auth and access side of things. There will be multiple applications that will use a JavaScript library that I'll be developing to talk and interact with my application. I'll be providing API keys to each of them, so that's not an issue.
Where I start getting confused is how to have the users on these sites authenticate to my application. It seems like a bad idea to have this external site store my user's account and password information; so, I guess I should have my JavaScript library include a login widget that asks for the user's account info for my application.
If authentication is successful there, since I'm working with a REST API, I'll need to store the token retrieved in a client side cookie or something so that the user doesn't need to login to my application again on every page of the external site. However, what happens if the user logs out of the external site, and then another user logs in from the same browser? As far as my JavaScript library is concerned, the old user would still be logged into my application, because the cookie/token would not have expired yet - how can I clear my cookie when the previous user's session ends? Or, am I completely off the right path here?
So, I'm thinking the process would be something like:
var token; // Some hashed string containing an expiration date and user id
var apiKey = '123abc';
// Read the cookie and check if it already contains the token
token = readCookie('token');
if (token == '') {
// get username and password from user through some prompt
var request_data = {apiKey: apiKey, user: username, pass: password};
$.post('https://service.com/api/user/login', request_data, function(data) {
token = data;
document.cookie = "token=" + token;
});
}
...
var get_data = {apiKey: apiKey, token: token};
$.get('http://service.com/api/<object>', get_data, function(data) {
// Do something with data
});
Sorry, there's several questions buried in here. I guess the main one is if I'm storing the token to a cookie, how do I ensure that it is cleared when the user logs off of the external application? Or, if I shouldn't be storing it to a cookie, how do I keep the client aware of the user's state?