django restframework token认证失败,"无效令牌"

时间:2017-11-06 13:02:30

标签: django authentication django-rest-framework jwt

我遇到令牌身份验证问题。 我用内置服务器的django运行我的django应用程序。

$python manage.py runserver

我的应用程序urls.py

from rest_framework_jwt.views import obtain_jwt_token
from .views import LectureCreateView

urlpatterns = [
    ...
    url(r'^api/user_auth/$', obtain_jwt_token),
    url(r'^api/lecture/create/$', LectureCreateView.as_view()),
]

我的应用程序的models.py

from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated

class LectureStartView(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (TokenAuthentication,)

    def post(self, request):
        ...

和settings.py

...
INSTALLED_APPS = [
...

    # Rest framework
    'rest_framework',
    'rest_framework.authtoken',


    'myApp',
]
...


REST_FRAMEWORK = {
    # other settings...

    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

我想要使用令牌进行身份验证。 我成功发行了令牌。

POST' ... api / user_auth /' {     "用户名":"测试",     "密码":" blahbalh123" }

{
      "token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjIwMTMyMzA2Iiwib3JpZ19pYXQiOjE1MDk5NzA5NjcsInVzZXJfaWQiOjMsImVtYWlsIjoiaW50ZXJydXBpbmdAbmF2ZXIuY29tIiwiZXhwIjoxNTA5OTcxNTY3fQ.acwqAP4sBPZWYPC0GfgL3AZarNz4Opb_5P4RewZJYrI"
}

但是我用令牌

失败了

请求:

POST ...api/lecture/create/ HTTP/1.1
Host: 127.0.0.1:8000
Authorization: Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjIwMTMyMzA2Iiwib3JpZ19pYXQiOjE1MDk5NzA5NjcsInVzZXJfaWQiOjMsImVtYWlsIjoiaW50ZXJydXBpbmdAbmF2ZXIuY29tIiwiZXhwIjoxNTA5OTcxNTY3fQ.acwqAP4sBPZWYPC0GfgL3AZarNz4Opb_5P4RewZJYrI

响应:

Status: 401 Unauthorized

Allow →GET, POST, HEAD, OPTIONS
Content-Length →27
Content-Type →application/json
Date →Mon, 06 Nov 2017 12:59:17 GMT
Server →WSGIServer/0.1 Python/2.7.13
Vary →Accept
WWW-Authenticate →Token
X-Frame-Options →SAMEORIGIN

{
    "detail": "Invalid token." 
}

我的代码出了什么问题? 对不起我的英语技能。

1 个答案:

答案 0 :(得分:1)

我认为你正在混合来自django-rest-framework和REST框架JWT的令牌。

在DJR文件中说:

from rest_framework.authtoken import views urlpatterns += [ url(r'^api-token-auth/', views.obtain_auth_token) ]

您应该用以下代码替换您的代码:

from rest_framework.authtoken import views from .views import LectureCreateView urlpatterns = [ ... url(r'^api/user_auth/$', views.obtain_auth_token), url(r'^api/lecture/create/$', LectureCreateView.as_view()), ]

我希望它可以帮到你。