【问题标题】:How add header for swagger generation based on annotation?如何为基于注释的招摇生成添加标题?
【发布时间】:2019-06-19 08:19:30
【问题描述】:

考虑例子:

@RequestMapping("myPath")
public Mono<MyDto> myMethod(@RequestParam(value = "amount") Long amount, @AuthenticationPrincipal MyUser user) {

} 

要从参数列表中跳过MyUser,我已将@AuthenticationPrincipal 添加到排除项和springfox 生成的类似这样的swagger 文档中:

"/myPath": {
  "get": {
    "tags": [
      "my-controller"
    ],
    "summary": "myMethod",
    "operationId": "myMethodUsingGET",
    "produces": [
      "*/*"
    ],
    "parameters": [
      {
        "name": "amount",
        "in": "query",
        "description": "amount",
        "required": true,
        "type": "integer",
        "format": "int64"
      }
    ],
    "responses": {
      "200": {
        "description": "OK",
        "schema": {
          "$ref": "#/definitions/Mono«MyDto»"
        }
      },
      "401": {
        "description": "Unauthorized"
      },
      "403": {
        "description": "Forbidden"
      },
      "404": {
        "description": "Not Found"
      }
    },
    "deprecated": false
  }
}

这里是弹簧配置:

@Configuration
@EnableSwagger2WebFlux
public class SwaggerConfig {
    @Bean
    public Docket api() {
        Class[] clazz = {AuthenticationPrincipal.class};

        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .paths(PathSelectors.any())
                .build()
                .ignoredParameterTypes(clazz);
    }
}

有没有办法在springfox 项目为@AuthenticationPrincipal 指定的每个路径生成的招摇文档中添加标题? 例如。忽略 MyUser 类作为参数(或参数组)并将其替换为标题(如 My-Auth-Header),用于找到 @AuthenticationPrincipal 的所有 @RequestMapping 方法。

【问题讨论】:

    标签: java spring-boot swagger-2.0 swagger-codegen springfox


    【解决方案1】:

    这是一个示例,如何使用名为 Auithorization 的 header 参数添加 JWT 令牌

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
        @Bean
        public Docket api() {
    
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
                    .globalOperationParameters(
                            Collections.singletonList(new ParameterBuilder()
                                    .name("Authorization")
                                    .description("JWT Authorization token")
                                    .modelRef(new ModelRef("string"))
                                    .parameterType("header")
                                    .required(false)
                                    .build()));
        }
    }
    

    【讨论】:

    • 但这会将Authorization 令牌添加到所有API,而不是@AuthenticationPrincipal 的方法。 :(
    • 没问题,不需要,如果不需要身份验证,则不会填充标题
    猜你喜欢
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2022-01-23
    • 2021-04-16
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    相关资源
    最近更新 更多