Skip to content

encode()/decode() key parameter type should not be str #602

@WolfgangFellger

Description

@WolfgangFellger

The jwt.encode() and jwt.decode() functions declare parameter key to be str. This seems to have been the case for a while, but with new release mypy will now complain that
Argument "key" has incompatible type "bytes"; expected "str" [arg-type]
when this parameter is given a bytes object.

Giving it a string does not seem to make sense though, the key is inherently binary (and indeed the first thing HMAC does is throw the key into force_bytes: https://github.com/jpadilla/pyjwt/blob/fdfd6871/jwt/algorithms.py#L173-174).

Everything works as intended when you pass in bytes, it's just the type declaration.

Expected Result

Parameter should accept bytes (and possibly not accept str)

Actual Result

mypy reports a type error when using bytes.
When using str it is impossible to pass random bits (since it will be run through .encode('utf-8'))

Reproduction Steps

import secrets
import jwt

secret = secrets.token_bytes(32)
token = jwt.encode(payload={"aud": "foobar"}, key=secret, algorithm="HS256")
result = jwt.decode(
    token,
    key=secret,
    audience="foobar",
    verify=True,
    algorithms=["HS256"],
    options={"require": ["aud"]},
)

Runs fine, but mypy will report errors.

Metadata

Metadata

Assignees

No one assigned

    Labels

    staleIssues without activity for more than 60 days

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions