简体   繁体   English

Spring 启动、Swagger 和授权

[英]Spring Boot, Swagger and Authorisation

I have a Spring Boot API that uses Springdoc (Swagger).我有一个使用 Springdoc (Swagger) 的 Spring 启动 API。 The API has security with "apiKey" and "code" fields being passed in the header. API 具有安全性,“apiKey”和“code”字段在 header 中传递。 I am having difficulty configuring Swagger correctly to enable the Authentication function in the Swagger UI.我在正确配置 Swagger 以在 Swagger UI 中启用身份验证 function 时遇到困难。 This is the configuration:这是配置:

@Bean
public OpenAPI alartaCoreAdtAPI() {
    return new OpenAPI()
            .addSecurityItem(new SecurityRequirement().addList("BASIC"))
            .components(
               new Components()
                   .addSecuritySchemes("BASIC",
                       new SecurityScheme()
                           .type(SecurityScheme.Type.HTTP)
                           .scheme("basic")
                           .name("code")
                                            
                   )
            )               

              .info(new Info().title(config.getApiTitle())
              .description(config.getApiDescription())
              .version(config.getApiVersion())
              .license(new 
             License().name(config.getApiLicenseTitle()).url(config.getApiLicenseUrl())))
);
  } 

I know this is incorrect, but are unsure how to configure it.我知道这是不正确的,但不确定如何配置它。

Any assistance appreciated.任何帮助表示赞赏。

To pass 2 custom headers of "apiKey" and "code" with every request为每个请求传递 2 个自定义标头“apiKey”和“code”

add this method:添加此方法:

private SecurityScheme securityScheme(String name) {
    return new io.swagger.v3.oas.models.security.SecurityScheme()
        .type(io.swagger.v3.oas.models.security.SecurityScheme.Type.APIKEY)
        .in(io.swagger.v3.oas.models.security.SecurityScheme.In.HEADER)
        .name(name);
} 

and replace your.components() block with following并用以下内容替换 your.components() 块

.components(new Components()
        .addSecuritySchemes("apiKey", securityScheme("apiKey"))
        .addSecuritySchemes("code", securityScheme("code"))
    )
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM