django - JSON:带有 django-rest-framework-json-api 和 JWT 的 API
问题描述
我认为在我的新项目中使用标准 JSON:API 可能是个好主意。不幸的是,我立即无法让 JWT 身份验证正常工作。我的设置:
- 姜戈
- Django REST 框架
- REST 框架 JWT 身份验证
- Django REST 框架 JSON API
如果我获得身份验证路径的选项:
{
"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"
}
]
}
如何正确检索令牌或正确使用上述软件包?
解决方案
您的有效负载不是有效的 JSON API 文档。它必须在键上有一个资源对象或资源对象的集合data
。一个资源对象必须有id
和type
成员。属性应表示为键上的属性对象attributes
。
报告的错误似乎与缺少type
成员有关。因此,它假定类型为None
,它是“不是构成由端点表示的集合的类型”。最后一部分似乎特定于Django REST Framework JSON API实现。
请注意,JSON API 规范与身份验证无关,因此取决于您的实施。您不必使用 JSON API 资源对象来表示凭据。JSON API 通常不用于与身份验证相关的端点,因为已实施的身份验证标准或已建立的约定建议该端点使用另一种有效负载结构。
推荐阅读
- android - 如何在新的 ViewPager2 中禁用 Fragment 的销毁?
- java - Replace an image resource on a jasperserver via Java REST API v7.2.0
- ios - 在照片应用程序和文件和文件夹应用程序中显示 iOS Cordova 应用程序文件
- kubernetes-helm - 在 azure AKS 上忽略 nginx-ingress Fluxcd HelmRelease 中的 loadBalancerIP 和注释
- amazon-web-services - 如何验证 Secrets Manager 凭证轮换是否成功
- typescript - 量角器打字稿测试 - Salesforce webdriver iframe
- install4j - 是否可以始终自动将命令行参数传递给 install4j 安装程序?
- javascript - 如何使 PDF.js 查看器滚动到 React 中的匹配项
- sql-server - 2 个表 - 尝试使用 RIGHT UNION,替换表 2 中的字段
- python - 如何禁用 Tkinter 中的按钮?