2

I have a private HttpOnly cookie that is encrypted with the user's id (this is used for authentication).

I also have a GET request route (let's call it GET X) that is ran when the page loads. But I only want it to run if the user is logged in.

It seems like there are two options, both of which are suboptimal.

Option 1) Run the route regardless when the site loads. If the user is not logged in then the route will 404 because the cookie will not be sent. This is fine, but it incurs the cost of a pointless request and shows up as a red 404 in the console.

Option 2) Do a GET request to the server first to check if the user is logged in. The server returns true or false by decoding the cookie and seeing if it is valid. When the client receives a response, if they're not logged in, then they just don't perform the GET X request. And if they are logged in then they don't.

The problem with Option 1 is that if the user is not logged in then GET X is sent pointlessly since it will just 404.

The problem with Option 2 is that there is added latency. That is, before GET X can be executed, we have to wait for the round trip from the server.

Is there an alternative solution? Ideally it would be possible to check for the existence of the HttpOnly cookie, and then if it didn't exist, to not send the request. But as far as I can tell it is not possible to do this. I'd like to avoid the roundtrip latency with Option 2, but also avoid the pointless 404's with Option 1. Is there a solution to this?

Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136
  • You cannot rely on the client to tell you if they're logged in or not because that's not secure. So, you definitely need a round trip to check if a user is actually logged in and have a valid auth cookie and based on the result, server response. Also, you cannot access HttpOnly cookie in order to avoid unnecessary requests. I think that's the best you can get with this config. A possible approach is to use JWT tokens instead of cookies because you can check their existence in local storage using javascript to avoid unnecessary requests. – Ajay Dabas Jan 01 '20 at 05:30

1 Answers1

1

To check for existence of the token httpOnly, you can try the trick mentioned here:https://stackoverflow.com/a/46957815

It's been working fine for me until iOS 14, then it stopped working for some reason. I haven't had time to dig into it yet but would be appreciate if someone could confirm the same issue.

Nghia Le
  • 343
  • 3
  • 10