Search code examples
javascriptcookiesjwt

jwt served via httponly cookie with someway to find out is-logged-in


While building a javascript SPA (single page application) I need to display some pages differently based on if the user is logged in or not.

Auth is handled by JWT which is served via httpOnly cookie and secure headers.

That leaves cookie not accessible from the SPA javascript and that in turn means I don't know if the user is logged in or not.

I did check some posts on how to solve this problem and found some suggestions like

  • send another cookie which is not httpOnly with some flag like session ID or user ID with expiry date and in the client side JS, use that cookie to see if the user is authenticated.

  • create an endpoint on API server, something like /is-logged-in and make a http call from JS to check if the user is authenticated or not before displaying the page.

  • store JWT locally without cookies (obviously a no go due to the security reasons and the amount of code I will have to write to mitigate all kinds of possible stealing attacks)

I am late to the SPA party but I am sure this has to be a long solved problem. I am unable to see something obvious I guess.

Please point me to the right direction.

For completeness, here are some unanswered, semi answered related posts


Solution

  • You have basically two choices:

    Save that the user is logged in with a second non-http cookie that expires

    Pros

    • No addition HTTP request required
    • No latency before you know if the user is logged in

    Cons

    • You need to keep the expiration and renewal of both cookies in sync
    • If your cookies are not in sync anymore because of an edge case, you will need to detect it and act accordingly

    Use an HTTP request that will tell you if the user is logged in or not

    Pros

    • Less error prone
    • No need to change the backend

    Cons

    • You still need to detect if the user is no longer logged in while the user is using the app