StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 18 · DRF Authentication & Permissions

Token Authenticated API

mediumDjango REST FrameworkDRF Authentication & Permissions—No data yet

Problem statement

In this Django project, give the API a way to log in to it. Build the token endpoint in app/auth.py and the project-wide authentication schemes in the REST_FRAMEWORK dictionary in project/settings.py, so a mobile client trades credentials for a key once and identifies itself with that key afterwards. Today there is one protected endpoint and no login at all: clients that cannot hold a browser session send an email address and a password on every single request. DRF bundles a token app and a token view, but its bundled credential serializer asks for a username, and this user model does not have one.

Requirements

Implement:

  • EmailAuthTokenView and the credential serializer it uses, in app/auth.py
  • the REST_FRAMEWORK default authentication classes in project/settings.py

The following are already implemented and provided: the accounts app, app/views.py, app/urls.py and project/urls.py. accounts.User is built on AbstractBaseUser, its only identity field is a unique email, it has no username field at all, and USERNAME_FIELD = "email"; AUTH_USER_MODEL already points at it. rest_framework.authtoken is already in INSTALLED_APPS, so the Token model and its migration are in place and you never create that table yourself. / is routed to app.views.home, the banner the Run button shows. /api/token/ is named api-token and routed to app.auth.EmailAuthTokenView, which today is a placeholder answering 501. /api/me/ is named api-me and routed to app.views.WhoAmIView, which is finished: it requires an authenticated user, returns {"email": request.user.email}, and sets no authentication_classes of its own, so it uses whatever REST_FRAMEWORK says the project defaults are. app/urls.py imports EmailAuthTokenView by that name, so the class keeps it.

1. The credentials this project accepts

  • The token endpoint accepts exactly two fields, email and password:
{"email": "ada@example.com", "password": "not-a-secret-1234"}
  • A request that sends username instead of email is not valid credentials, no matter what address it carries. A wrong password and an email nobody signed up with are not valid credentials either.
  • In all three cases the answer is 400, the body carries no token key, and no token row is created. The wording of the error is yours.

2. The token endpoint

  • Valid credentials answer 200 with the owner's key under the field name token:
{"token": "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567"}
  • The key belongs to the user, not to the call. The first valid request for a user creates their token row; every later one hands back that same key, and a user never ends up with two rows.
  • Two different users get two different keys, and each key is the one stored against that user.
  • The key the endpoint hands out is the key that then works on /api/me/.

3. The project's authentication schemes, in order

  • With the project-wide defaults set in REST_FRAMEWORK, an Authorization: Token <key> header on /api/me/ resolves request.user to the user that key belongs to, and two different keys resolve to their two different owners.
  • A session from Django's own login flow resolves request.user to the logged-in user with no Authorization header anywhere, and the token route and the session route report the same user.
  • A request with neither a token nor a session is refused with 401, and the response carries a WWW-Authenticate header that starts with Token.
  • A key that was never issued is refused the same way: 401 with that same WWW-Authenticate header, not 403.

Notes

  • A DRF view walks its authentication classes in order. The first one that recognises the request wins and sets request.user; one that sees nothing it understands returns None and the next is tried. TokenAuthentication reads an Authorization: Token <key> header and loads the key's owner; SessionAuthentication reads the session cookie Django's login flow set. Neither asks the other's question, so a project that wants both lists both.
  • The order decides the refusal. When nothing authenticates a request to a view that demands a user, DRF asks the first class in the list what challenge to advertise and puts the answer in WWW-Authenticate on a 401. SessionAuthentication has no challenge to offer, because a cookie is not something a server can ask for mid-request, so with it first DRF has no header to send and downgrades the refusal to a 403 - a "no" with no hint about how to say who you are.
  • Hand authenticate() the identity under its real keyword. Django's own backend reads USERNAME_FIELD off the user model, so the keyword that model declares is the one that works. Get the user from authenticate() rather than looking a row up and calling check_password on it yourself.
  • Raise a refusal as a serializers.ValidationError, which DRF renders as a 400: the submitted credentials are simply not valid data. AuthenticationFailed would answer 401, which is a different claim - that the request failed to authenticate for a resource, not that the body it posted was wrong.
  • Hand out keys with get_or_create, never by creating a fresh row per login. The bundled token view's machinery can be reused; only the credential fields change.
  • Only app/auth.py and project/settings.py change, and in settings only the REST_FRAMEWORK dictionary. Do not touch AUTH_USER_MODEL, INSTALLED_APPS or the given accounts app.
  • Set the schemes as the project default in REST_FRAMEWORK, not as authentication_classes on WhoAmIView: that file is read-only.
  • Do not write a permission class, a group, an authentication backend or a migration. IsAuthenticated on the given view is the whole policy here.

More in DRF Authentication & Permissions

See the module
Permission Class PoliciesEvery endpoint in this API is either wide open or locked to everyone, because no view and no project setting says who is allowed in. Name an authenticated-only project default, let anonymous clients read but not write the public catalog, and gate catalog writes on the model permissions the catalog editors group carries.—No data yetmediumObject Owner PermissionAny signed-in account can rewrite or delete anybody's post through this API, and one account's private drafts turn up in every other account's draft list. Write an object-level permission that lets owners write while everybody else only reads, and scope the drafts endpoint's queryset to the account making the request.—No data yetmediumShared Notes APIA notes API is read and rewritten by anybody who can reach it, because no scheme says who a caller is and no rule says what they may do. Accept both token and session authentication, let strangers read the shared record and nothing more, give each note's owner the only write, scope the private surface to its requester, and let the moderators group delete.—No data yetmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.