Search code examples
djangodjango-rest-frameworkdjango-rest-auth

Why django-rest-framework stores token in database?


Is token supposed to be stored only in client-side not in server-side?

from rest_framework.authtoken.models import Token

Django-rest have a model for token, that means token is stored in database. So why Django-rest store token in database?


Solution

  • It depends on the token type

    Some tokens are just a unique random string and the only way of knowing which user is associated with it is to store it somewhere and then look it up when needed.

    There is also another type of token which doesn't need to be stored. Basically, you encrypt the token string with a key and then send it to the user.

    The string must include some sort of data that you can find the user with.

    For example, you can create a token string like this: userID=2-some-random-string. Then you encrypt this string with a key and any algorithm you think that will work best for you and pass it to the user. When you receive the token from a user, all you need to do is to decrypt it using the key and extract the user id from that string. if there wasn't any user id or token failed to get decrypted, then the token is not valid.

    Django rest framework uses the first type of tokens which they need to be stored somewhere.

    There are other libraries for rest framework that works with other types of tokens. You can choose between all of them based on your needs or even you can create one yourself.