Home > Net >  Flask API security token with curl Python
Flask API security token with curl Python

Time:07-12

I am building a Flask server and I want to check for the access key when sending the curl request. Atm I am adding @token_required before every method and this way works good. However if I send a wrong request or something else happens it return "wrong key" or "token is missing". Is there any other way to implement it.

def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
    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:
        if token == app.config['SECRET_KEY']:
            return f(*args, **kwargs)
        else:
            return jsonify("wrong key"), 401
    except:
        return jsonify({'message':'Token is invalid'}), 401
return decorated

CodePudding user response:

This is how I usually implement jwt authorization. Note that I'm using the g global variable to store and share the user object between blueprints. Hope this helps.

def require_jwt(f):
"""
Decorator to require JWT token
"""

@wraps(f)
def decorated_function(*args, **kwargs):
    if request.method == 'OPTIONS':
        return jsonify({}), 204
    if 'Authorization' not in request.headers or not request.headers[
            'Authorization'].startswith('Bearer '):
        return jsonify({'error': 'Missing authorization header'}), 401
    token = request.headers['Authorization'].split(' ')[1]
    try:
        payload = jwt.decode(token,
                             current_app.config['SECRET_KEY'],
                             algorithms=['HS256'])
        user: User = User.query.filter_by(id=payload['id']).first()
        if not user:
            return jsonify({'error': 'Invalid token'}), 401
        else:
            g.user = user


    except jwt.ExpiredSignatureError:
        return jsonify({'error': 'Invalid token'}), 401
    except jwt.InvalidTokenError:
        return jsonify({'error': 'Invalid token'}), 401
    except Exception as ex:
        print(ex)
        return jsonify({'error': 'Invalid token'}), 401
    return f(*args, **kwargs)

return decorated_function
  • Related