【问题标题】:how to make the token active when the user is accessing the API如何在用户访问 API 时使令牌处于活动状态
【发布时间】:2020-04-22 05:58:29
【问题描述】:

我已经创建了一个基于 JWT 令牌的登录系统,我能够生成令牌并且我已经为该令牌添加了到期时间。

要求

  • 当用户访问 UI 时,令牌不应过期。

  • 当用户 10 分钟未访问 UI 时,令牌应过期。

我将 Angular 用于 UI,将 python 烧瓶用于后端,我不需要从哪里(UI 或后端)处理这个问题。我在想我们必须从 python 烧瓶中处理它,所以我使用了 python 和烧瓶标签,如果我错了,请告诉我。

我的后端代码:

def loginM(email, password):
     try:
       time_count = get_time_count_details()
       user = Credentials.query.filter_by(email=email).first()
       user_reg = Registration.query.filter_by(email=email).first()
       if bcrypt.check_password_hash(user.password, password):
           payload = {"email": user.email, 'user_id': user.user_id,
                      'first_name': user_reg.first_name,
                      'company': user_reg.company, 'mobile_num': user_reg.mobile_number,
                      'exp': time.time() + time_count}
        secret_key = open(SECRET_KEY).read()
        token = jwt.encode(payload, secret_key, algorithm='RS256').decode('utf-8')
        return dict(token=token)
    else:
        return dict(Unsucessful="Invalid Email Address and password")
except Exception:
    return False

【问题讨论】:

    标签: python-3.x flask


    【解决方案1】:

    您可以在 jwt 有效负载中使用 redis key expire 代替 exp

    • jwt 有效载荷不保存exp 值,jwt 不会过期。像这样的有效载荷:
    payload = {"email": user.email, 'eco_user_id': user.eco_user_id,
               'first_name': user_reg.first_name,
               'company': user_reg.company, 'mobile_num': user_reg.mobile_number,}
    
    • redis保存token,并设置过期时间为10分钟
    redis.set(token, user.id)
    redis.expire(token, 60 * 10)
    

    用户在访问api时,服务器会在redis中找到token,如果在redis中找到token,我们会刷新redis过期时间,否则返回403告诉用户登录

    【讨论】:

    • 这是什么“user.id”
    • user.id 是您用来获取用户实例的密钥。可能是emailmobile_number
    • 如果走这条路,你最好只使用 session,因为它们已经针对这些情况进行了很好的设计和测试。对于扩展 JWT,您可能想看看这个答案:stackoverflow.com/a/46284627
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多