关于 json 网络令牌的几个问题

A few questions about json web tokens

我最近开始使用 json 网络令牌,但我有一些未解决的问题

  1. 如果用户令牌在在线时过期会怎样?当他们请求下一个受保护的路由时,他们会被强制重新登录吗?如果是这样,感觉必须有办法解决这个问题,这样用户就不会随机注销

  2. 考虑到客户持有所有信息,您如何在 jwts 到期日期之前注销某人

任何对这 2 个问题的澄清将不胜感激

would they be forced to log in again when they request the next protected route?

如果没有其他信息将会话与登录用户相关联(例如,没有任何 cookie 或服务器可以使用的其他令牌),是。

是的,它不是很用户友好,而且 JWT 的到期时间通常很短。这个问题的一个常见解决方案是提供一个 refresh token as well,它可以存储在 HttpOnly cookie 中:

A refresh token has 2 properties:

  1. It can be used to make an API call (say, /refresh_token) to fetch a new JWT token before the previous JWT expires.
  1. It can be safely persisted across sessions on the client!

这样,客户端可以总是在任何时候都有一个有效的 JWT;他们不必重新登录,或注销然后重新登录。

how would you log someone out before the jwts expiration date considering the client holds all the info

您可以 在服务器上以某种方式将特定用户列入黑名单或忽略 JWT,直到他们再次登录。例如,在解析 JWT 之后,您可以检查服务器是否认为令牌仍然可用。如果不是,return 401 错误。

what would happen if a users token expires while they are online? would they be forced to log in again when they request the next protected route? and if so it feels like there has to be a way around this so that the user does not randomly get logged out

当您在网络应用程序中发出请求时,您需要拉入可用的令牌。所以答案是“你的应用程序做什么?”。您可以做很多事情,例如使用无效令牌发出请求,或者根本没有令牌。但显然这不是一个好主意。最好的策略是:

  1. 在每次 API 需要令牌的调用之前,检查当前令牌是否有效
  2. 如果令牌无效,请要求您的身份验证提供商获取新令牌。这称为 静默身份验证 。提供商如何处理这完全取决于他们,通常他们会为安全域保存一个 HttpOnly cookie,并且 return 一个新的 JWT。
  3. 如果静默验证失败,提供商会告诉您让用户登录。
  4. 此时最好的做法是使用他们以前使用的相同“登录策略”将用户重定向到身份验证提供程序,以获得新的“会话”和新的“令牌”。

how would you log someone out before the jwts expiration date considering the client holds all the info

注销与令牌过期完全分开。从用户的角度注销是:

  1. 告诉身份验证提供者删除 HttpOnly 安全 cookie
  2. 在浏览器中删除 JWT
  3. 更改 UI 以显示用户不再登录。

但这不会使令牌过期。令牌在到期日之前始终有效。如果您还想阻止使用该令牌,就好像它是有效的一样,您必须使用 AuthZ IAM 作为服务将令牌列入拒绝列表。例如,如果您使用 Authress 来管理访问控制,则 DELETE https://api.authress.io/v1/users/{userId}/tokens/{tokenId} 会导致使用该令牌对 return Forbidden 进行后续检查。但是,我要强调,令牌仍然有效,但您已采取措施将其标记为拒绝列出。