JSON:API 使用 django-rest-framework-json-api 和 JWT

JSON:API with django-rest-framework-json-api and JWT

我认为为我的新项目使用标准 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"
                }
            }
        }
    }
}

如果我然后尝试 POST 天真地使用 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"
        }
    ]
}

如何正确获取令牌或正确使用上述包?

您的负载不是有效的 JSON API 文档。它必须在 attributes 键上有一个 resource object or a collection of resource objects on data key. A resource object must have id and type members. Attributes should be represented as an attributes object

报告的错误似乎与缺少 type 成员有关。因此它假定类型为 None,即 "not the type that constitute the collection represented by the endpoint"。最后一部分似乎特定于 Django REST Framework JSON API 实现。

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