'Token always return invalid flask
I'm making a website application using flask as the backend and angular as the frontend, when I login I use token based with jwt but every time I call the token_required decorator it always returns "a valid token is missing" can anyone help me?
@app.route('/login', methods=['POST'])
def login_post():
if request.method == 'POST':
try:
login_data = request.get_json()
email = login_data['email']
password = login_data['password']
user = User.query.filter_by(email=email).first()
if user and check_password_hash(user.password, password):
token = jwt.encode(
{'public_id' : user.public_id, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=45)},
app.config['SECRET_KEY'])
login_user(user)
return jsonify({'token' : token}),200
except Exception as ex:
print(str(ex))
return jsonify({'message': 'invalid respond'}), 422
def token_required(f):
@wraps(f)
def decorator(*args, **kwargs):
token = None
if 'x-access-tokens' in request.headers:
token = request.headers['x-access-tokens']
if not token:
return jsonify({'message': 'a valid token is missing'})
try:
data = jwt.decode(token, app.config['SECRET_KEY'])
current_user = User.query.filter_by(public_id=data['public_id']).first()
except:
return jsonify({'message': 'token is invalid'})
return f(current_user, *args, **kwargs)
return decorator
i use this method to test the token
@app.route('/user', methods=['GET'])
@token_required
def authenticatedUser():
return jsonify("OK");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|