6

I'm having a little trouble with Token Authentication in the Django REST Framework. From the docs I know it is a matter of implementing the following:

from rest_framework.authtoken.models import Token

token = Token.objects.create(user=...)
print token.key

Now my question is, what exactly goes in the argument of Token.objects.create(user=...). The answer here helps and it says That will provide a Token model which is foreign-keyed to User. I'm not sure I understand this.

I have my own model of Users defined like so:

class Users(models.Model):
    userid = models.IntegerField(primary_key=True)
    username = models.CharField(max_length=255L, unique=True, blank=True)
    email = models.CharField(max_length=255L, unique=True, blank=True)
    password = models.CharField(max_length=64L, blank=True)
    registeredip = models.CharField(max_length=255L, blank=True)
    dob = models.DateField(null=True, blank=True)
    firstname = models.CharField(max_length=255L, blank=True)
    lastname = models.CharField(max_length=255L, blank=True)
    joindate = models.DateTimeField()

    class Meta:
        db_table = 'Users'

How would I create a token for users that satisfy certain conditions in this case?

# View Pseudocode
from rest_framework.authtoken.models import Token

def token_request(request):
    if user_requested_token() and token_request_is_warranted():
        new_token = Token.objects.create(user=request.user) #What goes here?

Any help or leads to any more documentation/examples would really help me out here. Thank you!

3
  • What's the error you're getting? It looks like the code is fine. Commented Aug 24, 2013 at 11:31
  • @kroolik It isn't an error per se. I'm just not sure what the argument should be in my case. Commented Aug 24, 2013 at 11:57
  • 5
    Token.objects.create(user=<your user instance>) creates a token for <your user instance>. You can insert this statement into your view where users request tokens passing request.user in place of <your user instace>. Make sure that request.user is an instance of User, not AnonymousUser. Commented Aug 24, 2013 at 12:26

1 Answer 1

3

to be sure: we are talking about Token authentication that is provided by django rest framework?

If so, this is very simple method, where there is a token (random 40 characters) that is used instead of username and password.

What is DRF delivering is a table (Token) where you need to create entries for your users, Token is referencing your user model (builtin or active custom model).

There are no tokens created initially, you need to create them.

There are several ways to create tokens, most common are:

  • create token for all users using signal handler (on create)
  • create tokens in background task (e.g. management tasks, runining from time to time and creates missing tokens)
  • have a special api endpoint, that will create token on-demand, with other user authentication method to authorize user

Basically that mean, that somewhere in your code you need to create Token instance, referencing your user instance.

Token(user=user).save()

Now, few remarks:

  • this implementation of tokens is rather rudimentary, e.g. you do not have any options to expire token, the only way is to regenerate token - this may be problematic if you want expiring sessions and/or multiple clients (remember - one token per user, not browser/session/device)
  • tokens are created using poor random function
  • tokens are stored in the database as plain text
  • there are multiple packages that deliver better and more secure token implementations, the most advanced are django-rest-framework-jwt and django-rest-knox (second one is simpler)

p.s. python class names should be singular (Users->User)

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

2 Comments

Is using urandom to generate tokens really insecure? I would think that keeping the tokens secret once they are generated would be a bigger issue. I didn't know that the default DRF tokens are stored as plain text. If you use django-rest-knox and your database is leaked, wouldn't an attacker still be able to find valid tokens by brute force?
this implementation is cryptographically weak, that's why ssh from begining is using it's own implementation; theoretically even existing strong hashers used in django can be brute-forced, so yes it is possible, question how much time it will take to break and in most cases - is this time is enough to detect, fix and expire all the tokens - for sure this is much better than no crypto at all; I'm using jwt tokens (from many reasons) and it is pretty neat; still waiting for HTTP Signature to be TheNewThing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.