jwt做用户登录认证

用户认证

背景

前后端分离项目中做用户认证,用户每次登录成功后返回一个token,下次访问时header带上返回的token证明改用户是登录过的,不需要再次登录,否则返回错误信息

  1. 重写装饰器做登录认证

    def authenticated(func):
          """
          重写tornado authenticated
          """
         @functools.wraps(func)
         async def wrapper(self, *args, **kwargs):
             res_data = {}
             token = self.request.headers.get("token")
             if token:
                 user = None
                 try:
                     jwt_data = jwt.decode(
                         token, self.settings["secret_key"],
                         leeway=self.settings["jwt_expires"], # 判断过期时间
                         options={"verify_exp": True} # 是否验证
                     )
                     user_id = jwt_data["id"]
                     user = await self.application.objects.get(User, user_id=user_id)
                 except Exception as e:
                     self.set_status(401)
                     res_data["content"] = "token error"
                 if user:
                     self._current_user = user
                     result = await func(self, *args, **kwargs)
                     return result
                 else:
                     self.set_status(401)
                     res_data["content"] = "token error"
             else:
                 self.set_status(401)
                 res_data["content"] = "miss token"
             self.write(res_data)
         return wrapper
    
  2. 登录成功后返回jwt_token

    def get_jwt_token(self,user_id):
       """
       fun : 使用jwt生成token
       :param user_id:
       :return:
       """
       payload = {
           "id": user_id,
           "iat": int(time.time()),
           "exp": int(time.mktime((datetime.datetime.now() + datetime.timedelta(minutes=60)).timetuple()))
       }
       jwt_token = jwt.encode(
           payload,
           self.settings["secret_key"],  # 进行加密签名的密钥
           algorithm="HS256",
           headers={"alg": "HS256",
                    "typ": "JWT"}
       ).decode("utf-8")
       return jwt_token
    
posted @ 2020-05-11 14:11  今日店休  阅读(253)  评论(0编辑  收藏  举报