Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Authentication classes Django doesn't try all the classes, fails at first

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'michan_api.utils.validators.ExampleAuthentication'
    ),

So I have this configured in my REST_FRAMEWORK setting in DRF. But it doesn't try all the classes.If the first one throws an exception it fails.

        for authenticator in self.authenticators:
            try:
                user_auth_tuple = authenticator.authenticate(self)
            except exceptions.APIException:
                self._not_authenticated()
                raise

This piece of code is responsible for this. (https://github.com/encode/django-rest-framework/blob/master/rest_framework/request.py#L373)

How do I make it try all the classes?

like image 676
Shruti Avatar asked Oct 21 '25 17:10

Shruti


1 Answers

Django REST framework documentation says:

The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise.

In some circumstances instead of returning None, you may want to raise an AuthenticationFailed exception from the .authenticate() method.

Typically the approach you should take is:

  • If authentication is not attempted, return None. Any other authentication schemes also in use will still be checked.
  • If authentication is attempted but fails, raise a AuthenticationFailed exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.

According the to django-rest-framework-jwt, it will not let you try another authentication if:

  • your token is invalid
  • your Authorization header does not match the syntax Authorization: <string> <string> with <string> being an actual string without whitespaces.

If your credentials do not meet that format, django-rest-framework-jwt will directly reject any authentication attempt. Depending on your requirements, you either need to fix your client credentials, either need to open an issue - or better open a pull request - on django-rest-framework-jwt.

like image 124
Linovia Avatar answered Oct 23 '25 08:10

Linovia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!