首页 > 解决方案 > JSON:带有 django-rest-framework-json-api 和 JWT 的 API

问题描述

我认为在我的新项目中使用标准 JSON:API 可能是个好主意。不幸的是,我立即无法让 JWT 身份验证正常工作。我的设置:

如果我获得身份验证路径的选项:

{
    "data": {
        "name": "Obtain Json Web Token",
        "description": "API View that receives a POST with a user's username and password.\n\nReturns a JSON Web Token that can be used for authenticated requests.",
        "renders": [
            "application/vnd.api+json",
            "text/html"
        ],
        "parses": [
            "application/vnd.api+json",
            "application/x-www-form-urlencoded",
            "multipart/form-data"
        ],
        "allowed_methods": [
            "POST",
            "OPTIONS"
        ],
        "actions": {
            "POST": {
                "username": {
                    "type": "String",
                    "required": true,
                    "read_only": false,
                    "write_only": false,
                    "label": "Username"
                },
                "password": {
                    "type": "String",
                    "required": true,
                    "read_only": false,
                    "write_only": true,
                    "label": "Password"
                }
            }
        }
    }
}

如果我然后尝试使用 Content-Type: application/vnd.api+json 天真地发布:

{
    "data": {
        "user": "user1",
        "password": "supersecretpw"
    }
}

我得到 409 冲突响应:

{
    "errors": [
        {
            "detail": "The resource object's type (None) is not the type that constitute the collection represented by the endpoint (ObtainJSONWebToken).",
            "source": {
                "pointer": "/data"
            },
            "status": "409"
        }
    ]
}

如何正确检索令牌或正确使用上述软件包?

标签: djangodjango-rest-frameworkjwtjson-apidjango-rest-framework-jwt

解决方案


您的有效负载不是有效的 JSON API 文档。它必须在键上有一个资源对象或资源对象的集合data。一个资源对象必须有idtype成员。属性应表示为键上的属性对象attributes

报告的错误似乎与缺少type成员有关。因此,它假定类型为None,它是“不是构成由端点表示的集合的类型”。最后一部分似乎特定于Django REST Framework JSON API实现。

请注意,JSON API 规范与身份验证无关,因此取决于您的实施。您不必使用 JSON API 资源对象来表示凭据。JSON API 通常不用于与身份验证相关的端点,因为已实施的身份验证标准或已建立的约定建议该端点使用另一种有效负载结构。


推荐阅读