郑文峰的博客 郑文峰的博客
首页
分类
标签
归档
关于
  • 导航 (opens new window)
  • 代码片段 (opens new window)
  • 收藏
  • 友链
  • 外部页面

    • 开往 (opens new window)
GitHub (opens new window)

zhengwenfeng

穷则变,变则通,通则久
首页
分类
标签
归档
关于
  • 导航 (opens new window)
  • 代码片段 (opens new window)
  • 收藏
  • 友链
  • 外部页面

    • 开往 (opens new window)
GitHub (opens new window)
  • 编程
  • python
  • tornado
zhengwenfeng
2022-08-10
目录

tornado 使用jwt完成用户异步认证

# 简介

在使用特定功能时,需要验证用户是否登录。使用jwt将用户不敏感的信息保存在客户端上,然后访问时,将加密的信息发送给服务端验证。

和session的不同之处在于,session需要在两端都存储,而jwt仅在客户端存储。

该项目的github地址: tornado_learning.git (opens new window)

# 栗子

创建异步验证的装饰器

从header中获取tsessionid的jwt token信息,然后从token获取用户id,从数据库中查找用户信息,再验证token是否过期。

代码: utils/authenticated_async.py

def authenticated_async(method):
    async def wrapper(self, *args, **kwargs):

        # ret_data = {}

        tsessionid = self.request.headers.get("tsessionid", None)
        if tsessionid:

            try:
                payload = jwt.decode(tsessionid, self.settings["secret_key"], leeway=self.settings["jwt_expire"],
                                     options={"verify_exp": True})

                user_id = payload["id"]
                try:
                    user = await self.application.objects.get(User, id=user_id)
                    self._current_user = user
                    await method(self, *args, **kwargs)
                except User.DoesNotExist as e:
                    self.set_status(401)
            except jwt.ExpiredSignatureError as e:
                self.set_status(401)

    return wrapper
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

在请求上添加用户认证

每次在请求该接口时,都需要对进行用户认证,认证通过才能访问该接口。

代码: apps/school/handle.py


from utils.authenticated_async import authenticated_async

class StudentHandler(BaseHandler):

    @authenticated_async
    async def get(self):
        id = self.get_argument("id", None)
        if not id:
            return self.write("please provide the 'id'")

        student = await self.application.objects.get(Student, id=id)

        try:
            self.write({
                "id": student.id,
                "name": student.name
            })
        except Student.DoesNotExist:
            raise tornado.webHttpError(404, "Object not found")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#python#tornado
上次更新: 2023/05/01, 18:02:43
最近更新
01
使用etcd分布式锁导致的协程泄露与死锁问题
05-13
02
基于pre-commit的Python代码规范落地实践
05-12
03
初识 MCP Server
05-01
更多文章>
Theme by Vdoing | Copyright © 2022-2025 zhengwenfeng | MIT License | 赣ICP备2025055428号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式