2

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.

3
  • something like JWT (?) Commented Oct 27, 2020 at 9:08
  • not like JWT i guess, in JWT user requests the token 1st. i want to keep token permanent. i have updated the description, if that helps. @Alviandoh Commented Oct 27, 2020 at 9:47
  • so technically if we "steal" the method of rest_framework Token generate their own token, and save it in your table. and then create custom backend based on their backend. It'd be fine? Commented Oct 27, 2020 at 9:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.