简体   繁体   English

DRF令牌认证教程

[英]DRF Token Authentication Tutorial

I am pretty new to Django, but I want to learn how to implement a DRF Token Authentication with Angularjs. 我是Django的新手,但是我想学习如何使用Angularjs实现DRF令牌认证。 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 我的代币验证童车代码: Github

In settings.py 在settings.py中

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

In signals.py 在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 在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 在urls.py中

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

To call using the angularjs; 用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. 对于令牌认证,有一个漂亮的django-rest-framework-jwt-安装和设置很简单。 To help with Angular JS looks like there is drf-angular-jwt (which uses DRF-JWT but I have not used it). 为了帮助使用Angular JS,似乎有drf-angular-jwt (它使用DRF-JWT,但我没有使用过)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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