Issue
I have read the Django Rest Framework Guides and done all the tutorials. Everything seemed to make sense and work just how it should. I got basic and session authentication working as described.
django rest framework - api guide
However, I'm struggling with the Token Authentication part of the documentation, it's a little lacking or does not go into as much depth as the tutorials.
django-rest-framework - token authentication
It says I need to create tokens for users but does state where in models.py?
Can someone explain the Token Authentication part of the documentation a little better for a first-timer?
Solution
No, not in your models.py -- on the models side of things, all you need to do is include the appropriate app (rest_framework.authtoken
) in your INSTALLED_APPS
. That will provide a Token model which is foreign-keyed to User.
What you need to do is decide when and how those token objects should be created. In your app, does every user automatically get a token? Or only certain authorized users? Or only when they specifically request one?
If every user should always have a token, there is a snippet of code on the page you linked to that shows you how to set up a signal to create them automatically:
@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
(put this in a models.py file, anywhere, and it will be registered when a Django thread starts up)
If tokens should only be created at certain times, then in your view code, you need to create and save the token at the appropriate time:
# 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)
Once the token is created (and saved), it will be usable for authentication.
Answered By - Ian Clelland
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.