首页 > 解决方案 > 使用 SpringFox 的 Swagger 中未列出 OAuth2 授权端点

问题描述

我使用 Spring Security 5 为 Swagger 构建 OAuth2 登录和 SpringFox。

有一个端点/oauth2/authorization/my-oauth,但是这个端点没有出现在/swagger-ui/. 如何让它出现在swagger-ui?需要登录的端点也不正确。

端点的工作方式类似于重定向到应该由浏览器打开的 Google/Facebook/Github 登录网页,但 Swagger 显示

在此处输入图像描述

已经尝试了解决方案https://stackoverflow.com/a/45921169/3952994但它不起作用并且端点仍然没有出现。

相关代码:

@Configuration
@EnableSwagger2
class SwaggerConfig {
   
   @Bean
   fun api() = Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.any())
      .paths(PathSelectors.any())
      .build()
      .apiInfo(apiInfo())
@Configuration
@EnableWebSecurity
class OAuth2SecurityConfig @Autowired constructor(
   private val myAuthRequestResolver: MyAuthRequestResolver,
   private val myAccessTokenResponseClient: MyAccessTokenResponseClient): WebSecurityConfigurerAdapter() {

   override fun configure(http: HttpSecurity) {
      http.authorizeRequests()
         .antMatchers("/v1/token**")
         .authenticated()
         .and()
         .csrf()
         .disable()
         .oauth2Login()
         .authorizationEndpoint()
         .authorizationRequestResolver(myAuthRequestResolver)
         .and()
         .tokenEndpoint()
         .accessTokenResponseClient(myAccessTokenResponseClient)
   }
}
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.3.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
       <dependency>
         <groupId>io.springfox</groupId>
         <artifactId>springfox-boot-starter</artifactId>
         <version>3.0.0</version>
      </dependency>

标签: springspring-bootspring-securityspringfox

解决方案


您可以使用以下代码添加Authorization标题

@Bean
public Docket api() {
    
    Docket docket = new Docket(DocumentationType.SWAGGER_2).select()
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .apiInfo(apiInfo())
                .build()
                
        docket.globalRequestParameters(Arrays.asList(
                new RequestParameterBuilder().name("Authorization")
                        .description("Authorization details for security JWT token")
                        .in(ParameterType.HEADER).required(false).build()));
    return docket;
}

推荐阅读