1

I am using PHP, AJAX, and JS for my PWA development. I want the user's logged-in state to stay persistent when he/she come back to the PWA app. Right now I am doing it via the help of the Access token and saving it in the cookie with HttpOnly via PHP. Defining it here -

  1. User enters details, and log in to the app.
  2. That details sent to the PHP backend, via AJAX.
  3. Backend login code check that details from database and if matched, then code create a random hashed token.
  4. Backend code save that hash to the cookie with HttpOnly and secure flag.
  5. User then prompted with a successfully logged-in message.
  6. When the next time the user comes back to the web app, the server PHP code looks for that login hashed value saved in a cookie and finds the relevant user from Database.
  7. If a match found, the user successfully logged-in.

So now my concerns are -

  1. Is this whole process secure and the same as what gets implemented in Industry.
  2. If not, then what can be the best way to achieve this with security.
Shivam Shukla
  • 73
  • 1
  • 11
  • 1
    Make a db column for users to store latest login user agent `$_SERVER['HTTP_USER_AGENT']`, after a user wants to login, check for num rows if == 1 else destroy session and set db column for user_agent to null, is this what your trying to acheive ?, could explain more maybe? – Vandalin Dec 22 '20 at 12:52
  • but that will detect the browser, I just want to know that whatever process I am doing to keep user logged-in is secure or not. – Shivam Shukla Dec 22 '20 at 12:56
  • You can save user in `localstorage` using javascript – Robin Singh Dec 22 '20 at 13:12
  • You're doing it correctly. – kosmosan Dec 22 '20 at 13:18
  • @RobinSingh `localStorage` does not send through request like `cookies` and need a different scenario. – Asef Hossini Aug 29 '21 at 21:27

1 Answers1

2

You can find the answer you are looking for here:)

"Keep Me Logged In" - the best approach

It is important to use an hashed cookie.

On the client side you should use a cookie that represnting the "id" of the "hashed" cookie,

When the next time the user comes back to the web app -> you will check his cookie("id") with the hashed cookie you saved on the server and check for a match(done on server side).

Note: the hashed function is done on your server.
One more thing: never let that cookie(hashed) leaves the server.

LIOR
  • 56
  • 6
  • So is there any security threat of cookie stealing, as anyone who get the cookie will set it from different device and then user will be logged in. Is this the same way facebook or instagram implement keep logged in. – Shivam Shukla Dec 22 '20 at 16:51
  • 2
    Yes, the cookie can be stolen, but you can provide additional security if you check the user's last IP and browser user agent. In the case something mismatch, warn the user by email, like many services do. – kosmosan Dec 23 '20 at 09:10