I’ve got a node.js REST service running on mongoose and express. I’m also using merse to get my routing set up.
What I’d like to achieve now are the following types of sceanrios:
Scenario I: e.g. blogpost
- GET -> no authentication required
- POST/PUT/DELETE -> authentication required
Scenario II: e.g. user
- GET -> authentication required
- POST/PUT/DELETE -> authentication required plus username of logged in user has to match
I’ve allready had a look at everyauth and mongoose-auth, but couldn’t find anything which would give me this kind of control.
Forget about everyauth. This library is an overkill, imho. Implementing authentication is quite simple actually, follow the schema:
usernameandpasswordto the server;usernameandpasswordand checks in DB whether there is a user with thatpassword. If there is no user, just respond with an error;req.session.regenerateand in the callback doreq.session.userID = user.id. Express will automatically send the cookie to the user;req.session.userID. If it finds one, then store it inreq, i.e.req.user = user;req.uservariable is set. If it is, then we are authenticated. And you’re done!ad 1+2) To make authentication safe, you should use some cryptography (and/or HTTPS). For example, the password should be held in DB in two parts:
saltandhash.saltis generated randomly (at the time of registration) andhash = hash_it(pwd, salt), wherehash_itis some hashing algorithm (for example: MD5 or SHA256).Now client side authentication can be made in several steps (only if you can use JavaScript):
new_saltto the login page (or generate one in JavaScript, there is no need to hide generating algorithm);give me salt for user Xand server responds with thesaltstored in DB (thesaltis public);pwdwithsaltand then hash the result again withnew_salt, store it in variablehpwd;username,hpwdandnew_saltto the server;pwdfrom DB forusername, hashespwdwithnew_saltand compares the result tohpwd(note: you do not storenew_salt).This method is nice, since every time you log in a random (from the external point of view) data flows through net, even though the
usernameand thepasswordis the same.This is important, because
passwordleak is a serious thing. Not because someone can break your app’s account (that’s a minor damage, unless you’re a bank – but then you wouldn’t ask such questions 😀 ). Mostly because people tend to use the same passwords for multiple sites, including bank accounts.