对于我正在从事的一个新的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 使用指定的令牌创建数据库。

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


当前回答

如果“注销所有设备”选项是可接受的(在大多数情况下是):

将令牌版本字段添加到用户记录中。 将此字段中的值添加到存储在JWT中的声明中。 每次用户注销时增加版本。 在验证令牌时,将其版本声明与存储在用户记录中的版本进行比较,如果不相同则拒绝。

无论如何,在大多数情况下都需要db访问以获取用户记录,因此这不会给验证过程增加太多开销。与维护黑名单不同,在黑名单中,由于需要使用连接或单独调用、清除旧记录等,数据库负载非常重要。

其他回答

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.

在内存中做一个这样的列表

user_id   revoke_tokens_issued_before
-------------------------------------
123       2018-07-02T15:55:33
567       2018-07-01T12:34:21

如果您的令牌在一周内过期,则清除或忽略更早的记录。同时只保留每个用户的最新记录。 列表的大小取决于您保留令牌的时间以及用户撤销令牌的频率。 仅当表发生变化时才使用db。在应用程序启动时将表加载到内存中。

我只是保存令牌到用户表,当用户登录时,我将更新新的令牌,当auth等于用户当前jwt。

我认为这不是最好的解决方案,但对我来说是可行的。

如果您希望能够撤销用户令牌,您可以跟踪DB上所有发出的令牌,并检查它们在类似会话的表上是否有效(存在)。 缺点是每次请求都要访问DB。

我还没有尝试过,但我建议使用以下方法来允许令牌撤销,同时将DB命中保持在最小值-

为了降低数据库检查率,根据某种确定性关联将所有已发行的JWT令牌分成X组(例如,按用户id的第一个数字分为10组)。

每个JWT令牌将保存组id和令牌创建时创建的时间戳。例如,{"group_id": 1, "timestamp": 1551861473716}

服务器将在内存中保存所有组id,每个组都有一个时间戳,该时间戳指示属于该组的用户的最后一次注销事件是什么时候。 例如,{"group1": 1551861473714, "group2": 1551861487293,…}

使用带有较旧组时间戳的JWT令牌的请求将被检查是否有效(DB hit),如果有效,将发出一个带有新时间戳的新JWT令牌供客户端将来使用。 如果令牌的组时间戳较新,则相信JWT (No DB hit)。

So -

We only validate a JWT token using the DB if the token has an old group timestamp, while future requests won't get validated until someone in the user's group will log-out. We use groups to limit the number of timestamp changes (say there's a user logging in and out like there's no tomorrow - will only affect limited number of users instead of everyone) We limit the number of groups to limit the amount of timestamps held in memory Invalidating a token is a breeze - just remove it from the session table and generate a new timestamp for the user's group.

使用刷新jwt…

我采用的一种比较实用的方法是在数据库中存储一个刷新令牌(可以是GUID)和对应的刷新令牌ID(无论进行多少次刷新都不会改变),并在生成用户的JWT时将它们作为用户的声明添加。可以使用数据库的替代方案,例如内存缓存。但我用的是数据库。

然后,创建一个JWT刷新Web API端点,客户机可以在JWT到期之前调用该端点。当调用刷新时,从JWT中的声明中获取刷新令牌。

在对JWT刷新端点的任何调用中,在数据库上验证当前刷新令牌和刷新令牌ID为一对。生成一个新的刷新令牌,并使用刷新令牌ID替换数据库上的旧刷新令牌。记住它们是可以从JWT中提取出来的声明

从当前JWT中提取用户的声明。开始生成一个新的JWT的过程。将旧的刷新令牌声明的值替换为新生成的刷新令牌,该刷新令牌也是新保存在数据库上的。完成所有这些后,生成新的JWT并将其发送给客户端。

因此,在使用了刷新令牌之后,无论是目标用户还是攻击者,在数据库上使用未与其刷新令牌ID配对的/刷新令牌的任何其他尝试都不会导致生成新的JWT,从而阻止任何拥有该刷新令牌ID的客户端不再能够使用后端,从而导致此类客户端(包括合法客户端)的完全注销。

这解释了基本信息。

The next thing to add to that is to have a window for when a JWT can be refreshed, such that anything outside that window would be a suspicious activity. For example, the window can be 10min before the expiration of a JWT. The date-time a JWT was generated can be saved as a claim in that JWT itself. And when such suspicious activity occurs, i.e. when someone else tries to reuse that refresh token ID outside or within the window after it has already been used within the window, should mark the refresh token ID as invalid. Hence, even the valid owner of the refresh token ID would have to log in afresh.

如果在数据库上找不到与所提供的刷新令牌ID配对的刷新令牌,则表明刷新令牌ID应该无效。因为空闲用户可能会尝试使用攻击者已经使用过的刷新令牌。

如前所述,在目标用户之前被攻击者窃取和使用的JWT,在用户尝试使用刷新令牌时也会被标记为无效。

唯一没有涉及的情况是,即使攻击者可能已经窃取了JWT,客户端也从未尝试刷新它。但是这种情况不太可能发生在不受攻击者监管(或类似)的客户端上,这意味着攻击者无法预测客户端何时停止使用后端。

如果客户端发起常规注销。应该通过注销从数据库中删除刷新令牌ID和相关记录,从而防止任何客户端生成刷新JWT。