The Open Event Server uses JWT based authentication, where JWT stands for JSON Web Token. JSON Web Tokens are an open industry standard RFC 7519 method for representing claims securely between two parties. [source: https://jwt.io/]
Flask-JWT is being used for the JWT-based authentication in the project. Flask-JWT makes it easy to use JWT based authentication in flask, while on its core it still used PyJWT.
To get the identity when a JWT token is present in the request’s Authentication header , the current_identity proxy of Flask-JWT can be used as follows:
@app.route('/example') @jwt_required() def example(): return '%s' % current_identity
Note that it will only be set in the context of function decorated by jwt_required(). The problem with the current_identity proxy when using jwt_required is that the token has to be active, the identity of an expired token cannot be fetched by this function.
So why not write a function on our own to do the same. A JWT token is divided into three segments. JSON Web Tokens consist of three parts separated by dots (.), which are:
The first step would be to get the payload, that can be done as follows:
token_second_segment = _default_request_handler().split('.')
The payload obtained above would still be in form of JSON, it can be converted into a dict as follows:
payload = json.loads(token_second_segment.decode('base64'))
The identity can now be found in the payload as payload[‘identity’]. We can get the actual user from the paylaod as follows:
def jwt_identity(payload): """ Jwt helper function :param payload: :return: """ return User.query.get(payload['identity'])
Our final function will now be something like:
def get_identity(): """ To be used only if identity for expired tokens is required, otherwise use current_identity from flask_jwt :return: """ token_second_segment = _default_request_handler().split('.') missing_padding = len(token_second_segment) % 4 payload = json.loads(token_second_segment.decode('base64')) user = jwt_identity(payload) return user
But after using this function for sometime, you will notice that for certain tokens, the system will raise an error saying that the JWT token is missing padding. The JWT payload is base64 encoded, and it requires the payload string to be a multiple of four. If the string is not a multiple of four, the remaining spaces can pe padded with extra =(equal to) signs. And since Python 2.7’s .decode doesn’t do that by default, we can accomplish that as follows:
missing_padding = len(token_second_segment) % 4 # ensures the string is correctly padded to be a multiple of 4 if missing_padding != 0: token_second_segment += b'=' * (4 - missing_padding)
- Real Python: Token Based Authentication With Flask
- Real Python: JWT Authentication with Python and Flask
You must log in to post a comment.