首页 > 解决方案 > How to create self defined token in Django Token Auth

问题描述

Can we create a self-defined token in the Token Auth in Django?

Currently, we are creating a super-user and generating a token for that super-user. But there are several environments and we want to keep the token same for all environments. Hence, a self-defined token is needed.

For example, if we create token using Token Auth

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}

we first create a superuser, then we create a token using django-admin.

Authorization:Token 8b000baba908hh7cf0618d492896e7b4bd6c9ce3

Here, I want to define my own token which will be saved in the same table.

标签: pythondjangodjango-rest-frameworkdjango-authentication

解决方案


If I understand correctly your question, you would like to have the same token for superuser in many environments (different servers)? If that's true, then you can try to override the method for automatic creation the tokens.

How to generate the tokens: https://www.django-rest-framework.org/api-guide/authentication/#generating-tokens

DRF AuthToken code https://github.com/encode/django-rest-framework/blob/master/rest_framework/authtoken/models.py

Based on the above the example code can be (not tested):

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        if instance.is_superuser:    
            Token.objects.create(user=instance, key="superuser_key")
        else:
            Token.objects.create(user=instance) # use generated key 

Important Please do not hardcode the token in the code, you can use for example python-decouple package to handle it as env variable.


推荐阅读