Skip to content

Commit

Permalink
Merge pull request #41 from alejandrogarza/log_exception_when_attempt…
Browse files Browse the repository at this point in the history
…ing_to_decode_jwt

For debugging purposes: Log exception when JWT Verification fails
  • Loading branch information
Bono de Visser authored Jul 17, 2020
2 parents eb55edc + 41c813a commit de85585
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
4 changes: 4 additions & 0 deletions oidc_auth/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from jwkest import JWKESTException
from jwkest.jwk import KEYS
from jwkest.jws import JWS
import logging
import requests
from requests import request
from requests.exceptions import HTTPError
Expand All @@ -16,6 +17,8 @@
from .settings import api_settings
from django.utils.translation import ugettext as _

logger = logging.Logger(__name__)


def get_user_by_id(request, id_token):
User = get_user_model()
Expand Down Expand Up @@ -131,6 +134,7 @@ def decode_jwt(self, jwt_value):
id_token = JWS().verify_compact(jwt_value, keys=keys)
except (JWKESTException, ValueError):
msg = _('Invalid Authorization header. JWT Signature verification failed.')
logger.exception(msg)
raise AuthenticationFailed(msg)

return id_token
Expand Down
13 changes: 12 additions & 1 deletion tests/test_authentication.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.contrib.auth.models import User
import json

from jwkest import long_to_base64
from jwkest import long_to_base64, JWKESTException
from rest_framework.permissions import IsAuthenticated
from django.conf.urls import url
from django.http import HttpResponse
Expand Down Expand Up @@ -224,3 +224,14 @@ def test_with_invalid_signature(self):
auth = 'JWT ' + make_id_token(self.user.username)
resp = self.client.get('/test/', HTTP_AUTHORIZATION=auth + 'x')
self.assertEqual(resp.status_code, 401)

@patch('oidc_auth.authentication.JWS.verify_compact')
@patch('oidc_auth.authentication.logger')
def test_decode_jwt_logs_exception_message_when_verify_compact_throws_exception(self, logger_mock, verify_compact_mock):
auth = 'JWT ' + make_id_token(self.user.username)
verify_compact_mock.side_effect = JWKESTException

resp = self.client.get('/test/', HTTP_AUTHORIZATION=auth)

self.assertEqual(resp.status_code, 401)
logger_mock.exception.assert_called_once_with('Invalid Authorization header. JWT Signature verification failed.')

0 comments on commit de85585

Please sign in to comment.