I am new to flask. I was trying to set the refresh tokens signing key as the users hashed password. I only want the refresh tokens signing key to contain the users hashed password and not the access token. I went through the flask_jwt_extended docs and came across the encode_key_loader
method here.
However I am not sure how I change what the function returns base of the type of the token. This is what I have so far.
@jwt.encode_key_loader
def my_key_loader(identity):
hash = fetch_user_password(identity)
return "somerandomsecretkey" + hash
I just need to way to figure out if the type of the token being generated and then I can return the appropriate key.
It's a bit hacky, but you could accomplish this via something like (untested):
@jwt.user_identity_loader
def user_identity_lookup(identity):
return identity['user'].id
@jwt.encode_key_loader
def custom_encode_key(identity):
secret = "<YOUR_NORMAL_JWT_ENCODE_KEY>"
if identity['token_type'] == "access":
return secret
else:
return secret + identity['user'].hashed_password
@jwt.decode_key_loader
def custom_encode_key(jwt_headers, jwt_payload):
secret = "<YOUR_NORMAL_JWT_ENCODE_KEY>"
if jwt_payload['type'] == "access":
return secret
else:
user = User.query.filter_by(id=jwt_payload["sub"]).one()
return secret + user.hashed_password
@app.route("/login", methods=["POST"])
def login():
user = User.query.filter_by(username='example').one()
access_token = create_access_token({'user': user, 'token_type': 'access'})
refresh_token = create_access_token({'user': user, 'token_type': 'refresh'})
return jsonify(access_token=access_token, refresh_token=refresh_token)
You could also use the Flask.g
object to to store what type of token you are making in a global variable, but I think that would probably be worse then the above solution.