0

For context, I am attempting to create a JWT used to send notification requests to Apple Push Notifications server, as described here and here. Following the gists, I've attempted to decode the token generated by the jwt.encode() method. I wasn't sure why the gists did this, because PyJWT Docs state this method returns a str. In fact, the top answer to a similar question points this out.

However, if I don't attempt to decode the token, I receive a TypeError: Object of type bytes is not JSON serializable when I attempt to package the token as a request header:

def generate_token() -> str:
    token = jwt.encode(
        {...}
    )

    return token

def push_notification():
    auth_token = generate_token()
    headers = {"authorization": f"Bearer {auth_token}"}
    ...
    response = await client.post(url, headers=headers, json=payload) # Traceback TypeError here

Note that the payload argument contains a dictionary of strings, there are no bytes here:

    payload_data = {
        "aps": {
            "alert": {
                "title": "Air Quality Alert",
                "subtitle": "Your Air Quality Has recently exceeded WHO guidelines",
                "body": "This is a test notification"
            },
            "sound": "default",
            "category": "AIR_QUALITY",
            "interruption-level": "active"
        },
    }

    payload = json.dumps(payload_data).encode('utf-8')

As the title of the question states, if I do attempt to decode the token then an AttributeError is thrown: str' object has no attribute 'decode':

"authorization":f"bearer{auth_token.decode('ascii')}" 
AttributeError: 'str' object has no attribute 'decode'
John Harrington
  • 1,314
  • 12
  • 36
  • Looks like it used to be `bytes`: https://github.com/jpadilla/pyjwt/pull/521#issuecomment-760677034 , https://github.com/jpadilla/pyjwt/commit/5d33b041f2aeccc653436958c08187f1bd538d94 – cosmic_inquiry Nov 02 '22 at 02:31
  • Please be aware that you are here `f"bearer{auth_token.decode('ascii')}"`running into the next problem, because there should be a space between "Bearer" (usually with uppercase B) and the token., eg. "Bearer eyJ....". Right now the space is missing. – jps Nov 02 '22 at 07:59
  • @jps The error output in the console strips the whitespace, but excellent eye and I have fixed the capitalization. Thank you. – John Harrington Nov 02 '22 at 14:08

0 Answers0