使用DRF的令牌身份验证无效

时间:2018-05-31 12:57:26

标签: django authentication django-rest-framework token

我是DRF(Django Rest Framework)的初学者。 我试图在我的api调用中使用Token进行身份验证。

我已经这样做了:

1-创建新用户时:

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

# This code is triggered whenever a new user has been created and saved to the database
@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)

2-创建:

./manage.py createsuperuser --email f.user@blahblah.com --username fabrice

2个表格( authtoken_token auth_user )没问题。

但是当我调用API时,如果没有添加令牌,则api正在运行:(:

$ http -a fabrice:azerty12 http://127.0.0.1:8000/firerisk/highway/
HTTP/1.1 200 OK
Allow: GET
Content-Length: 179
Content-Type: application/json
Date: Thu, 31 May 2018 12:49:10 GMT
Server: WSGIServer/0.2 CPython/3.5.2
Vary: Accept
X-Frame-Options: SAMEORIGIN

[
    {
        "id": 1,
        "name": "XXX"
    },
    {
    ...
    ...

但是,只有这个电话必须工作,不是吗? :

http -a fabrice:azerty12 http://127.0.0.1:8000/firerisk/highway/ 'Authorization: Token a840a16a3cd43e346f7a3e1442fce0acdf51d609'

而且,如果我不使用身份验证,则失败没关系

$ http http://127.0.0.1:8000/firerisk/highway/
HTTP/1.1 401 Unauthorized
Allow: GET
Content-Length: 58
Content-Type: application/json
Date: Thu, 31 May 2018 12:25:44 GMT
Server: WSGIServer/0.2 CPython/3.5.2
Vary: Accept, Cookie
WWW-Authenticate: Basic realm="api"
X-Frame-Options: SAMEORIGIN

{
    "detail": "Informations d'authentification non fournies."
}

更新:

我的settings.py:

    # the REST Framework
    'rest_framework',
    'rest_framework.authtoken',
    'django_extensions',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    )
}

和一个ViewSet(ModelViewSet):

class HighwayViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows highway to be viewed
    """
    serializer_class = HighwaySerializer
    # Authentification !
    permission_classes = (IsAuthenticated,)
    queryset = Highway.objects.all().order_by('name')
    # Only 'get' method
    http_method_names = ['get']

我错了?

感谢您的帮助。

F。

1 个答案:

答案 0 :(得分:0)

您需要先学习基础知识。什么是HTTP,什么是HTTP头,什么是Django会话(它不是HTTP头,会话的内容不影响头),阅读令牌认证的Django REST Framework文档。

如果要在浏览器中测试视图,请在DRF DEFAULT_AUTHENTICATION_CLASSES配置变量中明确允许Django Session身份验证。它可以与令牌认证共存。

除非您使用RESTClient或DHC或REST Easy之类的插件,否则无法为HTTP请求添加普通Web浏览器附加标记。

您正在向Django会话添加令牌,但您已在DRF中禁用了会话身份验证,即使您启用它,DRF也不会从Django会话中读取令牌,因为API客户端无法将令牌添加到Django会话。即使DRF会从Django会话中读取令牌,但由于客户端无法控制内容,因此完全没有意义。