How to implement login required decorator in Flask

后端 未结 2 1279
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 08:27

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 f

2条回答
  •  一向
    一向 (楼主)
    2020-12-15 08:42

    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.

    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
    

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

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

    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.

提交回复
热议问题