简体   繁体   English

jwt 通过 httponly cookie 提供,以某种方式找出是否已登录

[英]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.在构建 javascript SPA(单页应用程序)时,我需要根据用户是否登录以不同方式显示某些页面。

Auth is handled by JWT which is served via httpOnly cookie and secure headers.身份验证由 JWT 处理,它通过 httpOnly cookie 和安全标头提供服务。

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.这使得 cookie 无法从 SPA javascript 访问,这反过来意味着我不知道用户是否已登录。

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.发送另一个不是 httpOnly 的 cookie,带有一些标志,如会话 ID 或具有到期日期的用户 ID,并在客户端 JS 中使用该 cookie 来查看用户是否已通过身份验证。

  • 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.在 API 服务器上创建一个端点,例如/is-logged-in并从 JS 进行 http 调用以在显示页面之前检查用户是否已通过身份验证。

  • 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)在没有 cookie 的情况下在本地存储 JWT(由于安全原因和我必须编写的代码量来减轻各种可能的窃取攻击,这显然是不行的)

I am late to the SPA party but I am sure this has to be a long solved problem.我参加 SPA 派对迟到了,但我相信这必须是一个长期解决的问题。 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为了完整起见,这里有一些未回答的、半回答的相关帖子

You have basically two choices:您基本上有两种选择:

Save that the user is logged in with a second non-http cookie that expires保存用户使用过期的第二个非 http cookie 登录

Pros优点

  • No addition HTTP request required不需要额外的 HTTP 请求
  • 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您需要保持两个 cookie 的过期和更新同步
  • If your cookies are not in sync anymore because of an edge case, you will need to detect it and act accordingly如果您的 cookie 由于边缘情况而不再同步,您将需要检测它并采取相应措施

Use an HTTP request that will tell you if the user is logged in or not使用 HTTP 请求来告诉您用户是否已登录

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您仍然需要检测用户在使用应用程序时是否不再登录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM