python - Django REST Framework Auth Token -


i'm having little trouble token authentication in django rest framework. docs know matter of implementing following:

from rest_framework.authtoken.models import token  token = token.objects.create(user=...) print token.key 

now question is, goes in argument of token.objects.create(user=...). answer here helps , says that provide token model foreign-keyed user. i'm not sure understand this.

i have own model of users defined 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 create token users satisfy conditions in case?

# view pseudocode rest_framework.authtoken.models import token  def token_request(request):     if user_requested_token() , token_request_is_warranted():         new_token = token.objects.create(user=request.user) #what goes here? 

any or leads more documentation/examples me out here. thank you!

to sure: talking token authentication provided django rest framework?

if so, simple method, there token (random 40 characters) used instead of username , password.

what drf delivering table (token) need create entries users, token referencing user model (builtin or active custom model).

there no tokens created initially, need create them.

there several ways create tokens, common are:

  • create token users using signal handler (on create)
  • create tokens in background task (e.g. management tasks, runining time time , creates missing tokens)
  • have special api endpoint, create token on-demand, other user authentication method authorize user

basically mean, somewhere in code need create token instance, referencing user instance.

token(user=user).save() 

now, few remarks:

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

p.s. python class names should singular (users->user)


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -