2
votes

We're using rest_framework.authentication.TokenAuthentication to authenticate API users in Django REST Framework using an access token.

Is there a way to use this same class to authenticate users for Django generally?

I've tried adding it straight in to AUTHENTICATION_BACKENDS but it doesn't work:

AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",

    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",

    'rest_framework.authentication.TokenAuthentication',
)

Is there a quick way to do this or do I need to write a custom authentication backend?

2

2 Answers

3
votes

Django REST framework authentication and permission classes require the use of Django REST framework views, as the authentication is done on the view level [1]. This is different from Django authentication backends, where the authentication is done through the middleware.

Is there a way to use this same class to authenticate users for Django generally?

No, Django REST framework authentication backends are distinctly separate from Django authentication backends, and the reverse is technically true [2].

[1]: There has been discussion of moving this to the middleware level, but this is not currently planned.
[2]: Django authentication backends can be used through SessionAuthentication and other comparable DRF backends.

0
votes

You can use SessionAuthentication.

AUTHENTICATION_BACKENDS = (
    # Use Django's session framework for authentication.
    'rest_framework.authentication.SessionAuthentication',
    ....
    'rest_framework.authentication.TokenAuthentication',
)