Search code examples
djangodjango-rest-frameworkdjango-users

Working with django rest framework to authenticate a user with new token for every login


I would like to use django-rest-framework token to authenticate users. My workflow would be:

  1. User requests a page

    • If auth token is present, respond with the requested data.
    • If auth token is not present, redirect to the login page (with the request page).
  2. Inside the login page, user submit their credentials

    • If credentials were correctly authenticated, get or create a token for that user and redirect back to the requested page with the token.
    • Else, respond with error.

Lastly,

  1. When the user logs out, delete the token for that user.

So my question is, is it okay to delete and create a new token for every login if the user has already logged out? Also I assume the token will be unique, am I correct? Your help and guidance is very much appreciated. Thank you.


Solution

  • A REST API should be stateless, that means that there should not be a "session" hence no login and no logout, and no redirections to a login page.

    If the request doesn't have a token then the API should return (probably) a 401 Unauthorized HTTP status code and not a redirection. You're making an API so there won't be human interaction. Django rest framework offers a human-friendly interface that does have sessions, login/logout, and if that's all you need the go for it, you can do whatever you want. But It'd be hard for another program to use your API.

    why not using tokens with expiration dates or using another well known authentication method ?? :P

    Hope this helps :)