【发布时间】:2018-05-31 12:57:25
【问题描述】:
我是 DRF(Django Rest 框架)的初学者。 我正在尝试在我的 api 调用中使用带有令牌的身份验证。
我已经做到了:
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',
)
}
和一个视图集(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.
【问题讨论】:
-
看来,如果我这样调用 api,它就可以工作(不提用户名/密码):http 127.0.0.1:8000/firerisk/highway'Authorization: Token a840a16a3cd43e346f7a3e1442fce0acdf51d609'。
标签: django authentication django-rest-framework token