为 Django 编写的两个 JWT 包都给我带来了文档质量差的问题,所以我尝试了 DRF-auth_token 包。这是我遵循的一个很好的例子,Django Rest Framework Token Authentication。理论上你应该可以去
localhost:8000/api-token-auth/
网址.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.models import User
from rest_framework.authtoken import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.urls', namespace='api')),
url(r'^orders/', include('orders.urls', namespace='orders')),
url(r'^api-token-auth/', views.obtain_auth_token, name='auth-token'),
]
为用户获取令牌不起作用,所以我自己重写了它以使其工作:
@api_view(['POST'])
def customer_login(request):
"""
Try to login a customer (food orderer)
"""
data = request.data
try:
username = data['username']
password = data['password']
except:
return Response(status=status.HTTP_400_BAD_REQUEST)
try:
user = User.objects.get(username=username, password=password)
except:
return Response(status=status.HTTP_401_UNAUTHORIZED)
try:
user_token = user.auth_token.key
except:
user_token = Token.objects.create(user=user)
data = {'token': user_token}
return Response(data=data, status=status.HTTP_200_OK)
我的版本有效:
http://localhost:8000/api/login/customer-login/
{"username": "thisguy@example.com", "password": "wombat"}
-->
{
"token": "292192b101153b7ced74dd52deb6b3df22ef2c74"
}
DRF auth_token 不起作用:
http://localhost:8000/api-token-auth/
{"username": "thisguy@example.com", "password": "wombat"}
-->
{
"non_field_errors": [
"Unable to log in with provided credentials."
]
}
设置.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# third party:
'django_extensions',
'rest_framework',
'rest_framework.authtoken',
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
似乎设置正确。我数据库中的每个用户都有一个令牌。每个用户都is_authenticated
在is_active
数据库中。超级用户可以获得他们的令牌:
localhost:8000/api-token-auth/
{"username": "mysuperuser", "password": "superuserpassword"}
-->
{
"token": "9297ff1f44dbc6caea67bea534f6f7590d2161b0"
}
出于某种原因,只有超级用户才能获得令牌:
localhost:8000/api-token-auth/
{"username": "regularguy", "password": "password"}
-->
{
"non_field_errors": [
"Unable to log in with provided credentials."
]
}
为什么我的用户无法登录并获取他们的令牌?谢谢