'PHP password_hash() / password_verify() and persistent connections

I am working on a new authentication system for my PHP website, using "password_hash" and "password_verify" functions.

However, many posts recommend using a 'token' system for persistent authentication.

  • Is it unsafe to store the password_hash in a Cookie? If yes, why? (so far as I understand, it is impossible to 'decode' a password hashed with this PHP function)
  • If the previous solution is acceptable, is there any way to compare 2 hashes of the same string? ("password_hash" function will generate a new string every time it is called)

I would also like to auto-login users when clicking on the "Dashboard" button in my e-mails - through a link like "[email protected]&pass_hash=XXX"

  • Is it unsafe? Why?

Thanks a lot for your enlightened help! :-)



Solution 1:[1]

Is it unsafe to store the password_hash in a Cookie? If yes, why? (so far as I understand, it is impossible to 'decode' a password hashed with this PHP function)

Yes, it's unsafe. Or at least, less safe than not doing it. If you expose the hash to the user, it enables out-of-band brute forcing. I.e., the user can attack the password offline. In addition, if the password doesn't change often, it allows the contents of the cookie to be copied and authenticated with.

is there any way to compare 2 hashes of the same string?

You shouldn't ever be directly comparing two hashes to authenticate, you should only be using the return value of password_verify().

If you want to "keep the user logged in", you'd generally authenticate on the first request, start a session, and then use the existence of the session as authentication for subsequent requests. (And then auto-expire the session after some amount of inactivity.)

I would also like to auto-login users when clicking on the "Dashboard" button in my e-mails - through a link like "[email protected]&pass_hash=XXX"

Is it unsafe? Why?

Yes, it's very unsafe. In this design, the hash is essentially no different than the password. Anybody in the world can click the link and they're logged in as the user, without having to know the password. And email can't be guaranteed to be secure, so this design is just as insecure as just emailing somebody a link with the plain password in it.

Anything that automatically logs in is insecure. Just embed a bare link to the target page and have the page make the user log in.

I need the authentication to last for few months.

This is a code smell. Nobody realistically expects an idle session to last a few months, especially with modern password managers that fill in the authentication for you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1