2

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 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - this is helpful. Presumably however one could create a custom authentication backend using something like `user = Token.objects.get(token=token_from_request_header).user' to get the user?
Yes, DRF backends are not much different from Django backends, you should just need to implement a few extra methods.
0

You can use SessionAuthentication.

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

3 Comments

SessionAuthentication doesn't allow users to authenticate with a Django Rest Framework token, does it? Just tested, and Django still thinks the user is unauthenticated...
Have you kept TokenAuthentication after SessionAuthentication?
I have - I'm using AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", 'rest_framework.authentication.SessionAuthentication,' 'rest_framework.authentication.TokenAuthentication', )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.