I am trying to create a secure login system using cookies. I have read a lot of articles and Stack Overflow questions on how to achieve that, but couldn't find anything usefull. Everyone is suggests different ways of achieving that, but those who seem reasonable and know what they are doing, I cant quite understand for some reason.
Can you please explain me, what is the best way to create a secure login system with cookies.
I have heard, that the best approach is tokens. But some people say, that you should add a token next to the user id in the token table in the database - and so what if a person logs in from different devices? Some say, you should track ip addresses for that - and so what if a person logs in from another ip? Some say, you should create a session and a cookie - but then whats the point of the session (If the cookie authenticates a person)...
I have seen a lot off questions where people asked similar questions, and in the answers, people were trying to explain what is the difference between cookies and sessions. I know all of the differences and all of the theory. I just cant understand the technique to make everything secure.
I just cant clearly understand how that system should logically work, so can you please explain that step by step to me. Thank you.
Since you're looking for the most secure solution (as of today's understanding), I'm professionally obligated to point to this blog post which explains the theory, and Gatekeeper which implements it.
Do's of Secure Login Systems
selector
and anidentifier
selector
andidentifier
in a HTTP cookie, set to httpOnly=true and secure=true so it's only accessible over HTTPS (and hidden to JavaScript)selector
and a hash (SHA256 is okay here) of theidentifier
in the token tableDon'ts of Secure Login Systems
random_bytes()
, and if you're using PHP 5, random_compat).Brief Security Analysis of the Above Advice
password_hash()
for password storage, andpassword_verify()
to authenticate against the stored hash, then you've accomplished defense-in-depth against an attacker dumping your entire databaseAll of the the popular attack vectors (interception, hash cracking, defeating a weak random number generator) and some theoretical attack vectors (timing leaks) are, thus, eliminated. A little bit of good security engineering goes a long way.
Keep in mind that even security advice must carry an expiration date, so if you read this answer many years in the future some of it may be rendered obsolete. Don't get complacent, better ways are constantly being discovered.