【问题标题】:Authorization header is not sending when using Swagger documentation on drf-spectacular在 drf-spectacular 上使用 Swagger 文档时未发送授权标头
【发布时间】:2022-08-14 09:16:53
【问题描述】:

我正在使用 drf-spectacular 来记录和测试我的端点。我的代码如下所示:

@extend_schema(
    parameters=[
        OpenApiParameter(name=\'Authorization\', description=\'Authorization token\', required=True, type=str, location=OpenApiParameter.HEADER),
        OpenApiParameter(name=\'my-key1\', description=\'My key 1 info\', required=True, type=str, location=OpenApiParameter.HEADER),
        OpenApiParameter(name=\'my-key2\', description=\'My key 2 info\', required=True, type=str, location=OpenApiParameter.HEADER),
    ],
    description=\'Info about the endpoint\',
    responses={
        200: inline_serializer(
                name=\'Successfull response\',
                fields={
                    \"result_code\": serializers.IntegerField(default=200),
                    \"result_description\": serializers.CharField(default=\"Transaccion Exitosa\"),
                    \"data\": DocumentSerializer(many=True),
                }
            ),                         
    },
)
@api_view([\"GET\"])
def my_endpoint_function(request):
    pass

如您所见,我声明了 3 个标头参数,Authorizationmy-key1my-key2。 但是当我尝试使用 Swagger 文档时,只有 my-key1my-key2 正在发送。这是一个例子:

正如您在 Swagger 文档中看到的那样,我正在发送我上面提到的三个标头,但在 curl 中只有两个标头正在发送。 有谁知道如何解决这一问题?我需要在文档中测试我的端点。 感谢您的时间。

  • 您是否有右上角的“授权”按钮可让您设置此标题?它应该为您在 REST_FRAMEWORK 配置中的 authentication_classes 自动生成该标头。

标签: django django-rest-framework drf-spectacular


【解决方案1】:

我认为您需要使用屏幕右上角的“授权”按钮。

我能够复制这种行为 - 授权标头不是从视图发送的,而是从内置授权功能发送的。

  • 可以存在多个选项
  • View.authentication_classes 中使用的任何类都会显示
  • 您可能必须在值中手动输入JWTBearer 前缀

如果您有自定义身份验证,那么您可能需要研究如何执行customization in the documentation

class MyAuthenticationScheme(OpenApiAuthenticationExtension):
    target_class = 'my_app.MyAuthentication'  # full import path OR class ref
    name = 'MyAuthentication'  # name used in the schema

    def get_security_definition(self, auto_schema):
        return {
            'type': 'apiKey',
            'in': 'header',
            'name': 'api_key',
        }

我的屏幕截图中的一个是我的自定义一个,它是现有承载/jwt 令牌的副本,只是指定了我的自定义前缀。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 2022-11-08
    • 2017-12-04
    • 1970-01-01
    • 2021-02-09
    • 2022-10-16
    • 2018-07-12
    相关资源
    最近更新 更多