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

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

问题描述

我有2个可以一起使用的Flask应用程序(不同的项目).一个实现了一些使用令牌进行身份验证的API.第二个使用API​​并为其创建Web界面.现在,我有一个登录功能,可以将用户名和密码发送到API,如果正确,则返回auth令牌.获得令牌后,将其保存到用户会话中,现在应将用户视为已登录/已认证.在这种情况下,如何实现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.

这是我的登录功能-

 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.

推荐答案

另外,请查看有关装饰器的官方Flask文档: https://flask.palletsprojects.com/en/1.1.x/patterns /viewdecorators/或python文档 https://www.python. org/dev/peps/pep-0318/.

Also, 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.

您的装饰器应类似于:

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天全站免登陆