Yan Khonski
Yan Khonski

Reputation: 13083

Flask and PyJWT retrieve authorization header

There is a REST client that makes HTTP requests to the server. REST client sends a request which contains a header

Authorization=Bearer someValidBase64

Now I have a server application in Python 3.8, Flask 1.1.1, PyJWT==1.7.1.

@app.route(my_rest_end_point)
def get_service_payments():
    authorization_header = request.headers.get('Authorization')

    # It prints correctly: Bearer someValidBase64
    print("Authorization header:\n" + authorization_header)

    # Details from that header
    user_permissions = jwt.decode(authorization_header)

It fails with

File "/usr/local/lib/python3.7/site-packages/jwt/api_jws.py", line 188, in _load
    raise DecodeError('Invalid header padding')
jwt.exceptions.DecodeError: Invalid header padding

What I tried

authorization_header = request.headers.get('Authorization')
print("Authorization header:\n" + authorization_header)
cleared_header =  authorization_header[7:]
print("cleared_header:\n" + cleared_header)
user_permissions = jwt.decode(cleared_header)

It will print

Authorization header:
Bearer someValidBase64
cleared_header:
someValidBase64

It fails again because the token itself has structure someValidBase64.otherValidPart so there is a dot ..

Upvotes: 2

Views: 1277

Answers (1)

Karthick Mohanraj
Karthick Mohanraj

Reputation: 1658

Well, the problem is authorization_header consists of the value "Bearer someValidBase64". Now when you try to decode this, you are facing this error because the prefix "Bearer" is attached to it.

Make sure you store only the base64 part of the string inside authorization_header without the prefix so that you can decode it successfully.

Update:

As I understand, the authorization_header consists of a JWT token and since you're trying to decode a JWT token, make sure your authorization_header is in the format of xxxxx.yyyyy.zzzzz If you find it in any other format than this, make sure you strip the string so that only this format of the JWT token is extracted.

Upvotes: 2

Related Questions