微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Spring Boot 项目中为特定用户启用 Swagger UI

如何解决在 Spring Boot 项目中为特定用户启用 Swagger UI

我在 Spring Boot 中使用 Swagger UI 进行交互式 REST 端点表示。但是,每个知道其 URL 的人都可以访问 Swagger UI。是否有任何标准方法可以使用用户登录名或密钥来限制 Swagger UI 访问?我还使用 JWT 授权来保护休息休息端点。我使用的是 pringfox-swagger2 2.8.0。


@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
                .antMatchers("/api/shop/charity/details/**").permitAll().antMatchers("/api/shop/all/details/**")
                .permitAll()
                .antMatchers("/v2/api-docs","/configuration/ui","/swagger-resources/**","/configuration/security","/swagger-ui.html","/webjars/**")
                .permitAll()

                .anyRequest().authenticated();

}
@Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(customeUserDetailService);

    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }

private ApiKey apiKey() {
        return new ApiKey("jwtToken","Authorization","header");
    }
    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.basePackage("com.test.controller"))     
          .paths(PathSelectors.any())                          
          .build().apiInfo(testAPI()).securitySchemes(Arrays.asList(apiKey()));                                        
    }
    
    private ApiInfo testAPI() {
        return new ApiInfoBuilder()
                .title("REST API")
                .description("\"Sixty REST API \"")
                .version("2.0.0")
                .license("Apache License Version 2.0")
                .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"")
                .build();
    }
    
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/meta-inf/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/meta-inf/resources/webjars/");
    }


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。