如何手动使JWT令牌过期? [英] How to expire a JWT token manually?

查看:1445
本文介绍了如何手动使JWT令牌过期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题听起来很愚蠢,但是我仍然想知道我还能做些什么来实现此功能.

This question may sound stupid but I still wanna know what else I can do to achieve this functionality.

有一个作为 REST API 构建的清单系统,并且有两种类型的用户.

There's an inventory system built as a REST API and there are two types of users.

  1. users
  2. admins
  1. users
  2. admins

比方说,当用户登录时,给他一个包含以下信息的JWT令牌.

Let's say when an user logs in, he's given a JWT token that contain following information.

emailuser_iduser_level

此令牌在每个专用路由中解码,并检查用户是否已通过身份验证,还检查用户级别,以确保该用户有权访问该特定资源.

This token is decoded in each private route and checks if the user is authenticated and also checks the user level to make sure the user is authorized to access that particular resource.

让我们考虑一种特殊情况,管理员( Admin A )登录并开始在系统上进行一些管理工作.突然,另一个管理员( SuperAdmin )由于某种原因希望将管理员A 降级为普通用户. 但是,即使现在 Admin A 只是普通用户,他的令牌仍然是Admin令牌.因此,他仍然可以做管理工作,直到令牌在一小时内自动过期.

Let's consider a special scenario that an admin (Admin A) logs in and start doing some admin stuff on the system. Suddenly another admin (SuperAdmin) wants to downgrade Admin A to a normal user for some reason. However, even-though now Admin A is just a normal user, his token is still an Admin token. So, he can still do admin stuff until the token automatically expires in one hour.

那么,在这种情况下,手动使令牌失效的方式是什么?系统是否应该使用数据库查询来检查每个管理路由的用户级别?还是有其他方法可以实现这一目标?

So, in a scenario like this what's the way to expire that token manually ? Does the system should use a DB query to check user level for each admin route ? Or is there any other way to achieve this ?

希望您能清楚地理解这一点.

Hope you get this clearly.

推荐答案

一种可行的解决方法是维护一个缓存,该缓存由JWT/自发布其初始JWT以来权限已更改的用户状态组成.工作流程通常如下所示:

One viable way to handle this would be to maintain a cache consisting of JWT/state of users whose rights have been changed since their initial JWT were issued. The workflow would typically go something like this:

  • 您的系统向特定用户发布管理员JWT
  • 有一段时间,该管理员照常使用他的JWT
  • 然后,超级管理员决定将管理员降级.由于他无法撤消JWT,因此他将一个条目写入黑名单缓存,记录该用户不再是管理员.
  • 从现在开始,服务器将首先根据黑名单缓存检查所有传入请求,以决定要使用哪些信息.对于示例管理员,服务器将发现一个缓存条目,然后仅向该用户授予正常的非管理员权限.
  • 假设您的JWT到期,缓存最终将删除过时的JWT,从而使内存占用空间尽可能小.

这里关于缓存的关键是它的速度快.访问缓存中的条目应该比访问数据库快大约100倍.至于使缓存中的过期条目过期,许多缓存实现(例如Redis)允许设置条目被写入时的过期时间.在这种情况下,服务器将使用原始JWT内部的exp声明来设置到期时间.如果设置正确,则可以将缓存的内存需求降至最低.

The key point here regarding the cache is that it is fast. Accessing an entry in the cache should be roughly 100 times faster than hitting a database. As for expiring stale entries in the cache, many cache implementations, such as Redis, allow for setting the expiry of an entry when it gets written. In this case, the server would just set the expiry using the exp claim inside the original JWT. If setup properly, the memory requirements of the cache can be kept to a minimum.

这篇关于如何手动使JWT令牌过期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆