如何在 Flask 中实现登录所需的装饰器 [英] How to implement login required decorator in Flask

查看:28
本文介绍了如何在 Flask 中实现登录所需的装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个可以协同工作的 Flask 应用程序(不同的项目).一个实现了一些使用令牌进行身份验证的 API.第二个使用 API 并为其创建 Web 界面.现在我有一个登录功能,可以将用户名和密码发送到 API,如果正确,则获取身份验证令牌作为回报.获得令牌后,我将其保存到用户的会话中,现在应将用户视为已登录/已验证.对于这种情况,我如何实现 login_required 装饰器.

I have 2 Flask apps (different projects) that work together . One implements some API which uses tokens for auth. The second one consumes the API and makes a web interface for it. Now I have a login function that sends the username and password to the API, and if correct, gets the auth token in return. Once I have the token, I save it to the session of the user and the user should now be considered as logged in/ autheticated. How can I implement the login_required decorator for such a case.

这是我的登录功能 -

Here is my login function -

 def login(self):
        response = make_request(BASE_URL + 'login/', clean_data(self.data))
        if response.status_code == 200:
            session['auth_token'] = response.json().get('auth_token')
            return True
        return False

如何制作 login_required 装饰器?

How can I make the login_required decorator?

此外,如果重要的话,我正在使用 Redis 来存储会话.

Also I am using Redis to store sessions if that matters.

推荐答案

查看有关装饰器的官方烧瓶文档:https://flask.palletsprojects.com/en/1.1.x/patterns/viewdecorators/ 或 python 文档 https://www.python.org/dev/peps/pep-0318/ 也是.

Have a look at the official flask docs regarding decorators: https://flask.palletsprojects.com/en/1.1.x/patterns/viewdecorators/ or the python docs https://www.python.org/dev/peps/pep-0318/ as well.

您的装饰器应该类似于:

Your decorator should look something like:

from functools import wraps
from flask import abort
import jwt

def authorize(f):
    @wraps(f)
    def decorated_function(*args, **kws):
            if not 'Authorization' in request.headers:
               abort(401)

            user = None
            data = request.headers['Authorization'].encode('ascii','ignore')
            token = str.replace(str(data), 'Bearer ','')
            try:
                user = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])['sub']
            except:
                abort(401)

            return f(user, *args, **kws)            
    return decorated_function

...然后在你的 app.py 中你可能有:

... and then in your app.py you may have:

@app.route('/api/game', methods=['POST'])
@authorize
def create(user):
    data = json.loads(request.data)
    ....

在这种特殊情况下,我使用 JWT 作为令牌,您的令牌可以分别不同,令牌的解码可以是您的自定义实现,但基本机制与上面的示例非常相似.

In this particular case I have used JWT as token and your token can be different respectively the decoding of the token can be your custom implementation, but the basic mechanisms are pretty much as on the example above.

这篇关于如何在 Flask 中实现登录所需的装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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