lang2
lang2

Reputation: 11966

Flask: expire token on logging out

I'm using Flask with itsdangerous to implement token based login. It works fine but when user logs out with logout_user() call the token is still valid, causing inconsistency. So I'm trying to make the token expire too but couldn't find a proper way. Here is what I came up with:

def generate_auth_token(self, expiration):
    s = Serializer(current_app.config['SECRET_KEY'],
        expires_in=expiration)
    return s.dumps({'id': self.id}).decode('ascii')

@staticmethod
def verify_auth_token(token):
    import flask_login

    u = flask_login._get_user()
    if not u or isinstance(u, flask_login.AnonymousUserMixin):
        return None

    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
    except:
        return None
    return User.query.get(data['id'])

But I don't like this solution. Could somebody suggest a better way?

Upvotes: 1

Views: 2878

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159905

Ultimately, token-based authentication doesn't admit of easy particular invalidation. (Universal invalidation is easy - just change the SECRET_KEY used to sign the sessions - every session is automatically invalidated). There are several ways to make particular invalidation work:

  1. Store a random nonce on the user's profile and reset it every time they log out. Any token not containing the latest nonce is deemed invalid immediately.
  2. Store a set of revoked tokens (remove them once they expire to prevent the set from growing indefinitely) and check each token against this set. Add a user's token to the set when they log out and their token still has time on it.
  3. Issue short-lived tokens and provide an easy renewal flow (either at the API level or in your application) so that having 5 minute tokens doesn't impact the user's experience.

Upvotes: 7

Related Questions