对于我正在从事的一个新的node.js项目,我正在考虑从基于cookie的会话方法(我的意思是,将id存储到用户浏览器中包含用户会话的键值存储中)切换到使用JSON Web Tokens (jwt)的基于令牌的会话方法(没有键值存储)。

这个项目是一个利用socket的游戏。IO——在一个会话(web和socket.io)中有多个通信通道的情况下,有一个基于令牌的会话会很有用。

如何使用jwt方法从服务器提供令牌/会话失效?

我还想了解使用这种范例应该注意哪些常见的(或不常见的)陷阱/攻击。例如,如果这种模式容易受到与基于会话存储/cookie的方法相同/不同类型的攻击。

所以,假设我有以下内容(改编自this和this):

会话存储登录:

app.get('/login', function(request, response) {
    var user = {username: request.body.username, password: request.body.password };
    // Validate somehow
    validate(user, function(isValid, profile) {
        // Create session token
        var token= createSessionToken();

        // Add to a key-value database
        KeyValueStore.add({token: {userid: profile.id, expiresInMinutes: 60}});

        // The client should save this session token in a cookie
        response.json({sessionToken: token});
    });
}

口令登录:

var jwt = require('jsonwebtoken');
app.get('/login', function(request, response) {
    var user = {username: request.body.username, password: request.body.password };
    // Validate somehow
    validate(user, function(isValid, profile) {
        var token = jwt.sign(profile, 'My Super Secret', {expiresInMinutes: 60});
        response.json({token: token});
    });
}

--

会话存储方法的注销(或失效)需要更新KeyValueStore 使用指定的令牌创建数据库。

在基于令牌的方法中似乎不存在这样的机制,因为令牌本身将包含通常存在于键值存储中的信息。


当前回答

您可以在用户的文档/记录上的DB上有一个“last_key_used”字段。

当用户使用user和pass登录时,生成一个新的随机字符串,将其存储在last_key_used字段中,并在签名令牌时将其添加到负载中。

当用户使用令牌登录时,检查数据库中的last_key_used是否与令牌中的last_key_used匹配。

然后,当用户执行注销操作时,或者如果您想使令牌失效,只需将“last_key_used”字段更改为另一个随机值,随后的任何检查都将失败,从而迫使用户使用user登录并再次通过。

其他回答

在本例中,我假设最终用户也有一个帐户。如果不是这样,那么其他的方法也不太可能奏效。

创建JWT时,将其持久化到数据库中,并与正在登录的帐户相关联。这意味着您可以从JWT中提取关于用户的其他信息,因此根据环境的不同,这可能是可行的,也可能是不可行的。

对于之后的每个请求,不仅要执行您所使用的框架附带的标准验证(我希望)(验证JWT是否有效),还包括用户ID或另一个令牌(需要与数据库中的令牌匹配)之类的东西。

注销时,删除cookie(如果使用),并从数据库中使JWT(字符串)无效。如果不能从客户端删除cookie,那么至少注销过程将确保令牌被销毁。

我发现这种方法,加上另一个唯一标识符(数据库中有2个持久化项,可用于前端),会话具有很强的弹性

代币的有效期为1天 每天建立一个黑名单。 将无效/注销令牌放入黑名单

对于令牌验证,首先检查令牌的过期时间,如果令牌没有过期,则检查黑名单。

对于长会话需求,应该有一种机制来延长令牌过期时间。

上面的想法很好,但是有一种非常简单的方法可以使所有现有的jwt无效,那就是简单地改变秘密。

如果您的服务器创建了JWT,用一个秘密(JWS)对其进行签名,然后将其发送给客户端,简单地更改秘密将使所有现有的令牌无效,并要求所有用户获得一个新的令牌进行身份验证,因为他们的旧令牌突然根据服务器变得无效。

它不需要对实际的令牌内容(或查找ID)进行任何修改。

显然,这仅适用于当您希望所有现有令牌过期时的紧急情况,对于每个令牌过期,需要上述解决方案之一(例如短令牌过期时间或令牌内存储的密钥无效)。

我会在用户模型上保存jwt版本号的记录。新的jwt令牌将其版本设置为此。

在验证jwt时,只需检查它的版本号是否等于用户当前的jwt版本。

任何时候你想要让旧的jwt失效,只要改变用户的jwt版本号。

Haven't tried this yet, and it is uses a lot of information based on some of the other answers. The complexity here is to avoid a server side data store call per request for user information. Most of the other solutions require a db lookup per request to a user session store. That is fine in certain scenarios but this was created in an attempt to avoid such calls and make whatever required server side state to be very small. You will end up recreating a server side session, however small to provide all the force invalidation features. But if you want to do it here is the gist:

目标:

减少数据存储的使用(无状态)。 能够强制注销所有用户。 能力强制注销任何个人在任何时间。 在一段时间后要求密码重新输入的能力。 能够与多个客户一起工作。 当用户从特定客户端单击注销时,强制重新登录的能力。(为了防止有人在用户离开后“取消删除”客户端令牌-查看评论了解更多信息)

解决方案:

Use short lived (<5m) access tokens paired with a longer lived (few hours) client stored refresh-token. Every request checks either the auth or refresh token expiration date for validity. When the access token expires, the client uses the refresh token to refresh the access token. During the refresh token check, the server checks a small blacklist of user ids - if found reject the refresh request. When a client doesn't have a valid(not expired) refresh or auth token the user must log back in, as all other requests will be rejected. On login request, check user data store for ban. On logout - add that user to the session blacklist so they have to log back in. You would have to store additional information to not log them out of all devices in a multi device environment but it could be done by adding a device field to the user blacklist. To force re-entry after x amount of time - maintain last login date in the auth token, and check it per request. To force log out all users - reset token hash key.

这要求您在服务器上维护一个黑名单(状态),假设用户表包含禁止的用户信息。无效会话黑名单-是一个用户id列表。此黑名单仅在刷新令牌请求期间检查。只要刷新令牌TTL存在,条目就必须存在于该节点上。刷新令牌过期后,用户将被要求重新登录。

缺点:

仍然需要对刷新令牌请求执行数据存储查找。 无效的令牌可能会继续为访问令牌的TTL操作。

优点:

提供所需的功能。 在正常操作下,刷新令牌动作对用户隐藏。 只需要对刷新请求而不是每个请求执行数据存储查找。即每15分钟1次,而不是每秒1次。 最小化服务器端状态到一个非常小的黑名单。

With this solution an in memory data store like reddis isn't needed, at least not for user information as you are as the server is only making a db call every 15 or so minutes. If using reddis, storing a valid/invalid session list in there would be a very fast and simpler solution. No need for a refresh token. Each auth token would have a session id and device id, they could be stored in a reddis table on creation and invalidated when appropriate. Then they would be checked on every request and rejected when invalid.