How to implement login required decorator in Flask

大兔子大兔子 提交于 2019-11-29 09:47:36

问题


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

How can I make the login_required decorator?

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


回答1:


Also have a look on the official flask docs regarding decorators: http://flask.pocoo.org/docs/0.10/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.




回答2:


Given that each subsequent request will contain the API token, the decorator should do the following

  • Accept a generic request. You can use *args and **kargs for that
  • Extract the token from the header and compare it with the token stored in db (not Redis, but wherever the token generated is stored in the backend)
  • If authenticated, the *args and **kargs should be passed on to the decorated function
  • The output of the decorated function should then be returned as is
  • If the authentication failed, an error message should be returned.

For explanation on decorators, check out this link: http://thecodeship.com/patterns/guide-to-python-function-decorators/



来源:https://stackoverflow.com/questions/34495632/how-to-implement-login-required-decorator-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!