jazzband / djangorestframework-simplejwt

A JSON Web Token authentication plugin for the Django REST Framework.
https://django-rest-framework-simplejwt.readthedocs.io/
MIT License
4.03k stars 665 forks source link

Is possible to avoid raising a exception from the .authenticate() method? #763

Closed amolinaalvarez closed 1 year ago

amolinaalvarez commented 1 year ago

I have configured my project using the JWTAuthentication along with others authentication schemes:

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        ...
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        ...
    )
    ...
}

However, JWTAuthentication always raises an exception if the authentication does not succeed, thus preventing other authentication schemes from being checked. Is there a way to configure JWTAuthentication to return None instead of raising an exception?

A quick alternative would be to override the JWTAuthentication authenticate method, catching the exception and returning None:

def authenticate(self, request):
      try:
          return super().authenticate(request=request)
      except InvalidToken as exc:
          return None

Would this alternative be recommended, or could it potentially lead to undesirable security issues?

Thank you in advance.

Andrew-Chen-Wang commented 1 year ago

I recommend always just overriding and adding it to your configuration. In this case, I'm not sure whether you should/shouldn't, but I've used JWTAuthentication for awhile without issue with other auth methods.

There isn't a security concern with either approach, raising or not raising, so long as you unit test authentication using client class in Django such that a user with a malformed JWT is not authorized to interact with the service.