Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Django REST Framework provide different Authentication mechanisms

Why does Django REST Framework implement a different Authentication mechanism than the built-in Django mechanism?

To wit, there are two settings classes that one can configure:

  1. settings.AUTHENTICATION_BACKENDS which handles the Django-level authentication, and
  2. settings.REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'] which authenticates at the REST-Framework level

The problem I'm experiencing is that I have a Middleware layer which checks whether a user is logged-in or not.

When using a web client which authenticates via sessions, this works fine. However, from mobile or when running the test suite (i.e. authenticating using HTTP headers and tokens), the middleware detects the user as an AnonymousUser, but by the time we get to the REST Framework layer, the HTTP Authorization header is read, and the user is logged-in.

Why do these not both happen BEFORE the middleware? Furthermore, why doesn't REST Framework's authentication methods not rely on the Django authentication backend?

like image 376
BillyBBone Avatar asked Jun 30 '14 21:06

BillyBBone


People also ask

Which authentication is best in Django REST framework?

And these are all provided by drf(django rest framework) and other than these like oauth, oauth2 based authentication are provided by the efforts of the community with help of other python packages. And they can be easily used in the production environment.

What is basic authentication in Django REST framework?

Authentication is a mechanism that provides access control based on the credentials associated with incoming requests. Django REST Framework provides several authentication schemes.


1 Answers

Django Rest Framework does not perform authentication in middleware by default for the same reason that Django does not perform authentication in middleware by default: middleware applies to ALL views, and is overkill when you only want to authenticate access to a small portion of your views. Also, having the ability to provide different authentication methods for different API endpoints is a very handy feature.

Rest Framework's authentication methods do not rely on the Django authentication backend because the Django's backend is optimised for the common case, and is intimitely linked to the user model. Rest Framework aims to make it easy to:

  1. Use many different authentication methods. (You want HMAC based authentication? done! This is not possible with django auth framework)
  2. Serve API data without ever needing a database behind it. (You have a redis database with all your data in-memory? Serve it in milliseconds without ever waiting for a round trip to DB user model.)
like image 107
Thomas Avatar answered Oct 17 '22 02:10

Thomas