我需要使用 JSON Web Token 令牌的会话存储吗?为什么不只使用 cookie?

Do i need session store using JSON Web Token tokens ? Why not just using cookies?

我还是不明白JWT的主要目的是什么。至于我,唯一的目的是:


还有一种说法是,使用 JWT 您不必担心服务器端的会话存储。我不清楚。 JWT 怎么可能完全取代服务器端的会话存储?这是否意味着我们将所有会话数据放入 JWT,对其进行加密并在每次响应时将其发送给客户端?但如果是这样,是否意味着服务器发出的令牌会根据我们用于存储在会话中的数据而改变?据我所知,唯一阻止我们以这种方式使用 cookie(在服务器端没有会话存储)的是 cookie 文件的大小限制 - 仅 4kb.


还有我们还需要使用SSL来防止会话劫持吗? 请告诉我我的理解是否正确,或者还有其他方面的问题。

JWT 本身只是独立的令牌,不提供 CSRF 保护。用于交付 JWT 的协议可能(或应该)提供防止 CSRF 的方法。

JWT 比 cookie 显着 "better" 的一个领域是它们的跨域能力。您可以在此处阅读有关令牌和 cookie 之间比较的更多信息:https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

JWT 可以是独立的,因此它们将您需要的所有信息都放在一个可验证的容器中,这样您就可以在不存储它们(或对它们的引用)的情况下使用它们。但是会话中可能需要更多数据,因此通常避免会话存储本身并不是转向 JWT 的原因。

为了防止令牌泄露和会话劫持,需要 SSL。

我觉得关于JWT的传说太多了。要理解它的本质,还得回到它最初的定义。

根据其 official 网站:

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.

从本质上讲,JWT 提供的只是 a way to transmit data。不多也不少。由于涉及多方,格式必须标准化。一旦格式标准化,就可以创建库以促进其采用。

再次来自 official 站点:

When should you use JSON Web Tokens?

There are some scenarios where JSON Web Tokens are useful:

Authentication:

This is the typical scenario for using JWT, once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used among systems of different domains.

Information Exchange:

JSON Web Tokens are a good way of securely transmitting information between parties, because as they can be signed, for example using public/private key pairs, you can be sure that the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't changed.

因此,身份验证只是 JWT 的可能用例之一。虽然确实是JWT的典型用法。

在认证方面,可以使用JWT代替session+cookie的方式,因为它可以节省服务器存储session的内存。 但是收益有多大,要看用户量和你的具体场景。如果只有几个客户端并且没有 cross-domain 身份验证要求,我认为您不需要放弃良好的旧会话 + cookie 方法。

最后但并非最不重要的一点是,会话不仅仅用于身份验证。它实际上意味着 to place HTTP requests and responses within a larger context。鉴于 JWT 的大小限制,我不确定 JWT 是否可以为此目的替换会话。恕我直言,身份验证恰好是会话的用例之一,因为此类信息必须是user-specific。还有很多其他证明会话合理的好场景,例如购物车。