I configure the Flask-RESTful service and authenticate the user. The method I use:
def generate_auth_token(username, expiration=600):
gen_serial = Serializer(secret_key, expires_in=expiration)
return gen_serial.dumps({'username': username})
I pass the token to the user as follows:
class token(Resource):
decorators = [auth.login_required]
def post(self):
username = g.user
return_token = generate_auth_token(username)
return {'token':return_token.decode()}, 200
And the token is then checked as such, so it does not need to be stored on the server side:
def verify_auth_token(auth_token):
serial = Serializer(secret_key)
try:
data = serial.loads(auth_token)
except SignatureExpired:
return None
except BadSignature:
return None
serial_user = data['username']
return serial_user
This seems to work well, however, I don’t know how to log out before expiration without saving the token server. My idea was to return the garbage token when the user decided to log out, but I do not think this is an elegant or safe solution.
Any tips really will be helpful!
source
share