0

我通过 django rest 框架创建了一个简单的登录 API。下面是代码片段:

视图.py

from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny
from knox.views import LoginView as KLView
from knox.models import AuthToken

class loginAPIView(KLView):
    permission_classes = [AllowAny]
    
    def post(self, request, format=None):
        serializer = AuthTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        login(request, user)
        return super(loginAPIView, self).post(request, format=None)

URLS.py

from django.urls import path
from knox import views as knox_views
from .views import UserRegisterView, loginAPIView


urlpatterns = [
    path('register/', UserRegisterView.as_view(), name='register'),
    path('login/', loginAPIView.as_view(), name='login'),
    ]

现在,当我使用电子邮件和密码在邮递员中发出 POST 请求时。它抛出错误:

{
    "detail": "Invalid token."
}

注意::因为我使用 knox 来生成令牌。因此,当我进行新注册时,我也会获得令牌。请参阅下面的示例:

{
    "status": "OK",
    "message": {
        "email": "test.test@test.com",
        "first_name": "est",
        "last_name": "Sah",
        "employee_code": "6124368",
        "contact": "7500078619",
        "dob": null
    },
    "token": "db058f23ecc70f4fa3de4ac69a04dc48bb7579a63aea1ad3d038ce59b1511890"

我尝试了密码和令牌进行身份验证,但我得到了同样的错误。在运行开发服务器的 cmd 提示符中,我看到以下消息

[08/Apr/2021 15:26:33] "POST /apii/login/ HTTP/1.1" 403 27
Forbidden: /apii/login/

在邮递员原始正文中,我在 json 数据下方插入

{
    "email": "test.test@test.com",
    "password": "db058f23ecc70f4fa3de4ac69a04dc48bb7579a63aea1ad3d038ce59b1511890"
}

以下是 DRF 的 settings.py 内容

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        #'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'knox.auth.TokenAuthentication',
    ],
}

不知道我这样做是否正确,请提出建议。

httpie 输出

python.exe -m httpie 127.0.0.1:8000/apii/login/ 'Authorization: Token db058f23ecc70f4fa3de4ac69a04dc48bb7579a63aea1ad3d038ce59b1511890'

HTTP/1.1 405 Method Not Allowed
Allow: POST, OPTIONS
Content-Length: 40
Content-Type: application/json
Date: Thu, 08 Apr 2021 11:52:31 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.6.8
Vary: Accept, Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
    "detail": "Method \"GET\" not allowed."
}
4

1 回答 1

0

您是否尝试过在命令提示符下使用httpie发布?

$ http  http://127.0.0.1:8000/{your_path} 'Authorization: Token db058f23ecc70f4fa3de4ac69a04dc48bb7579a63aea1ad3d038ce59b1511890'
于 2021-04-08T11:25:10.437 回答