0

First let me start by saying, this is not a question of client token vs server-side session reference. I understand the differences and I've already decided on a session-less implementation.

I've also decided to use cookies for client-side persitance and transmission rather than localStorage, query param, auth headers, etc.

Ok, with that out of the way, I'm looking at two alternatives to save userID on the client. Both prevent tampering via signing of the data.

Express has a middleware which enables signed cookies, or I could use a JWT which also signs the data (which I would still send via a cookie).

So far, my thinking is to use signed cookies, it's got less processing overhead and does a specific thing and I don't necessarily need my data in nested json format. Also, I'm using it only for authentication of users on my webserver, not for API's or other authorization. I don't need a public/private asymmetric key validation.

JWTs are nice standards, and I will already be using it for OAUTH, but for my site auth, I don't need some of the benefits. For example, I don't need it for transferability. I will not have different sig algorithms or token types.

However I do appreciate that JWT's are a recognized standard and have lots of support/documentation.

Is there something I'm missing on why I should instead choose to use JWT's for website authorization and client identification?

BTW, I have done research on this before posting the question. Here is a very similar one, JWT vs cookies for token-based authentication

However the top voted answer doesn't apply for a few reasons. Chiefly, I've already decided to use cookies for JWT or not. I will be using cookies with options like sameSite to prevent CSRF attacks, along with: expires, secure, httpOnly, and signed (which is particular to express).

4

1 回答 1

0

到目前为止,我的想法是使用签名的 cookie,它的处理开销更少,并且做特定的事情,我不一定需要嵌套 json 格式的数据。此外,我仅将它用于对我的网络服务器上的用户进行身份验证,而不用于 API 或其他授权。我不需要公/私非对称密钥验证。

通过使用 cookie-parser 的签名选项,您的 cookie 将如下所示: user_id=111.base64Signature 这里的主要问题是您的令牌没有过期时间,所以即使您在 cookie 上设置了过期时间,如果 cookie 以 某种方式被盗并使用,您的服务器将接受这些请求。解决方案是在令牌本身上添加时间戳。所以现在你的有效载荷可能会被转换为 json 并且看起来像这样:

{
   userId: 111,
   exp: 1637437857
}

和饼干:token='{"userId":111,"exp":1637437857}'.base64Signature。所以现在如果你对有效负载进行 base64 编码,基本上这里与JWT的唯一区别是 header: token=header.payload.signature

关于性能,您将获得相同的结果(如果使用 json 格式作为有效负载),因为创建 hmac 的方法是节点的crypto.createHmac,并且在 express 中间件和常见 jwt 库(jsonwebtoken / express-jwt)中都使用对称签名。

我认为如果您决定实施过期,JWT 格式将使您能够使用不同的库并获得免费的验证检查(这似乎缺少 cookie-parser 中间件),如果您不需要这个,那么您的解决方案将完成这项工作.

于 2021-11-20T20:30:30.740 回答