简体   繁体   中英

How to put auth functionality in @app.before_request in flask

I want to make auth layer in flask app. I was using flask-jwt-extended for jwt auth so for that i have to mentioned @jwt_requied decorator for each protected route. so i dont want to do that for each protected route. I thought to define a function and make that to execute before each request by using @app.before_request. i want auth to happen in this layer.


def check_user_token():
    if 'x-access-token' in request.headers:
        token = request.headers['x-access-token']
    if not token:
        return jsonify({'message': 'Token is missing'}), 401

    try:
        data = jwt.decode(token, app.config['SECRET_KEY'])
        current_user = UserDetails.query.filter_by(username=data['username']).first()


    except:
        return jsonify({'message': 'Token is in-valid'}), 401
return current_user

So this the function i want to call before each request to check auth.

@app.before_request
def before_calback():
    #want to call that check_user_token() from here and 
   #also dont want to call that for 'login' route .
   #Once i will get some response from check_user_token() 
   #based on that want to proceed further
  #and  here i dont know to do this.

Basically my qns is how to do authentication in @app.before_request def before_calback()?

Can you access check_user_token()?

It would be like this

@app.before_request
def before_calback():
    check_user_token()

If you can post the some code, it would be easier to help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM