Skip to content

Commit e779af1

Browse files
committed
Raise an invalid token error when the incoming token has an unrecognized key id.
Key error isn't obviously incorrect, but looking at how it's used in the jwt package, it looks to generally be used for malformed keys, which I would expect to be a sign something was misconfigured, rather than a bad value from a client. By switching this to InvalidTokenError, we'll properly handle the error when authenticating. At present, we handle InvalidTokenError and some specific subclasses, but InvalidKeyError bubbles up as an unhandled error leading to a 500 error from Django. (InvalidTokenError and InvalidKeyError are siblings in the exception hierarchy, under PyJWTError.)
1 parent c9878a5 commit e779af1

File tree

2 files changed

+5
-5
lines changed

2 files changed

+5
-5
lines changed

src/rest_framework_jwt/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,9 +163,9 @@ def jwt_decode_token(token):
163163
try:
164164
keys = keys[kid]
165165
except KeyError:
166-
raise jwt.exceptions.InvalidKeyError
166+
raise jwt.exceptions.InvalidTokenError
167167
elif api_settings.JWT_INSIST_ON_KID:
168-
raise jwt.exceptions.InvalidKeyError
168+
raise jwt.exceptions.InvalidTokenError
169169
else:
170170
keys = list(keys.values())
171171

tests/views/test_authentication.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from django.utils.translation import ugettext_lazy as _
1111

1212
from jwt import get_unverified_header
13-
from jwt.exceptions import InvalidKeyError, InvalidAlgorithmError, InvalidSignatureError
13+
from jwt.exceptions import InvalidAlgorithmError, InvalidSignatureError, InvalidTokenError
1414

1515
from pytest import skip, fixture, raises
1616

@@ -352,7 +352,7 @@ def test_keys_key_id_not_found(
352352
secret_key = OrderedDict(hash3="three")
353353
monkeypatch.setattr(api_settings, "JWT_SECRET_KEY", secret_key)
354354

355-
with raises(InvalidKeyError):
355+
with raises(InvalidTokenError):
356356
assert JSONWebTokenAuthentication.jwt_decode_token(token) == None
357357

358358
def test_insist_on_key_id(
@@ -377,7 +377,7 @@ def test_insist_on_key_id(
377377

378378
# check if we insist on the key beging named
379379
monkeypatch.setattr(api_settings, "JWT_INSIST_ON_KID", True)
380-
with raises(InvalidKeyError):
380+
with raises(InvalidTokenError):
381381
assert JSONWebTokenAuthentication.jwt_decode_token(token) == None
382382

383383
def test_InvalidAlgorithmError():

0 commit comments

Comments
 (0)