Skip to content

Disallow custom authentication class to return user = None #9574

Open
@leandrodesouzadev

Description

@leandrodesouzadev

Hello there!
Currently it's allowed that an custom authentication class returns a tuple containing (None, None). This causes the authentication to be considered successful and sets request.user = None and this can cause errors that are hard to track where they came from.
I know that this wrongly implemented by the CustomAuthentication class, the user should've raised an AuthenticationFailed exception instead. But this allows the user to shoot itself on the foot.

Example of a bad implemented authentication class:

from rest_framework.authentication import BaseAuthentication

class MyDumbAuthentication(BaseAuthentication):
  def authenticate(self, request):
    return None, None

Later if you have a permission check for example, you would see the following error:

from rest_framework.permissions import BasePermission

class MyPermCheck(BasePermission):
  def has_permission(self, request, view):
    return request.user.has_perm("foo.bar")

# raises AttributeError("'NoneType' object has no attribute 'has_perm'")

It would be nice if rest framework disallowed this totally wrong implementation.

Checklist

  • Raised initially as discussion
  • This is not a feature request suitable for implementation outside this project. Please elaborate what it is:
    • compatibility fix for new Django/Python version ...
    • other type of bug fix
    • other type of improvement that does not touch existing code or change existing behavior (e.g. wrapper for new Django field)
  • I have reduced the issue to the simplest possible case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions