以JWT为主的无状态认证真的安全吗?

Is stateless authentication mainly using JWT is really secure?

这个问题我问了很久 JWT 真的安全吗?因为在对声明和有效负载进行编码方面,我们可以轻松解码令牌,并且该网站也很好地给出了这种解码。所以我的观点是任何人都可以使用 burpsuite 或任何其他工具简单地更改 auth header 并提供一些其他有效令牌并对假用户进行身份验证。像许多人推荐的那样将令牌存储在 localStorage 中,也可能不太安全。所以我的问题是,与加密的 cookie 或 session 相比,它真的安全吗?无状态身份验证的好处是什么?我看了很多文章说 JWT 对 Single Page App 有好处。是真的吗?

访问令牌通常在调用者提供其硬凭证(例如用户名和密码)后颁发。要访问受保护的资源,调用者需要将访问令牌发送到服务器以对每个请求执行身份验证。


在 Web 应用程序中,访问令牌不应由 JavaScript 访问,也不应存储在本地存储中。相反,访问令牌应该通过 HTTPS 连接发送并存储在设置了 Secure and HttpOnly 标志的 cookie 中:

4.1.2.5. The Secure Attribute

The Secure attribute limits the scope of the cookie to "secure" channels (where "secure" is defined by the user agent). When a cookie has the Secure attribute, the user agent will include the cookie in an HTTP request only if the request is transmitted over a secure channel (typically HTTP over Transport Layer Security (TLS)). [...]

4.1.2.6. The HttpOnly Attribute

The HttpOnly attribute limits the scope of the cookie to HTTP requests. In particular, the attribute instructs the user agent to omit the cookie when providing access to cookies via "non-HTTP" APIs (such as a web browser API that exposes cookies to scripts). [...]


在 JWT 中,有效负载是 JSON 编码为 Base64 的字符串。所以它不适合存储密码等敏感信息。

签名令牌允许服务器执行无状态身份验证,即仅通过检查访问令牌内容来判断用户是谁。服务器不会依赖外部服务来验证用户。

JWT 令牌应使用 强加密密钥 签名(必须在服务器上 安全 保存)并且签名必须是在信任令牌之前检查。