简体   繁体   中英

DRF Token Authentication Tutorial

I am pretty new to Django, but I want to learn how to implement a DRF Token Authentication with Angularjs. Some of the tutorials I have found haven't been too helpful in showing how to set it up, along with their source code etc...

Also, for production purposes, is it more practical to use a third party package? Or set up my own (it's for a personal project, so time contribution is not an issue).

My Buggy Code for Token Auth: Github

In settings.py

INSTALLED_APPS = (
    ...
    'rest_framework.authtoken'
)
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}

In signals.py

from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

In views.py

class ExampleAuthToken(APIView):
    def post(self, request, format=None):
        username = request.data.get("username")
        password = request.data.get("password")
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User.objects.create_user(username=username)
            user.set_password(password)
            user.save()
        content = {
            'user': unicode(user.username),
            'token': unicode(user.auth_token),
        }
        return Response(content)

In urls.py

urlpatterns = [
    url(r'^authtoken/', ExampleAuthToken.as_view(), name='authtoken'),
]

To call using the angularjs;

var credentials = {
  username: "root",
  password: "root123"
};

$.post("http://localhost:8000/authtoken/", credentials {
    success: function(data){
          console.log(data);
    }
}

I would definitely use a library. For token authentication there is the nifty django-rest-framework-jwt - it's straightforward to install and setup. To help with Angular JS looks like there is drf-angular-jwt (which uses DRF-JWT but I have not used it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM