接口方法上使用@PreAuthorize注解,Swagger UI 为什么不显示该接口?

发布于 2022-09-11 19:29:24 字数 2519 浏览 16 评论 0

1 问题描述

接口方法上使用@PreAuthorize注解,Swagger UI 上就不显示该接口;

如果删除方法上的所有@PreAuthorize注解,Swagger UI 上就显示这个接口了。

SecurityConfig已经放行了 Swagger 资源,如何使用 @PreAuthorize 注解,还能被 Swagger 扫描到?

2 相关代码

Swagger: 2.9.2

SpringBoot: 2.1.3.RELEASE

2.1 接口

@Api(value = "用户接口", tags = "User-API")
public interface UserApi {

    /**
     * 获取用户列表
     */
    @ApiOperation(value = "获取用户列表", notes = "获取用户列表")
    @GetMapping("/user/list")
    @PreAuthorize("hasRole('ROLE_SYSTEM')")
    ResultVO getUserList(@RequestBody UserReqVO userReqVO, Page<SysLogin> page);

@PreAuthorize("hasRole('ROLE_SYSTEM')") 会导致这个接口不在 Swagger UI 显示,去了就能显示。

2.2 Swagger2Config

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .useDefaultResponseMessages(false)
            .forCodeGeneration(true)
            .pathMapping("/")
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.xxx"))
            .paths(PathSelectors.any())
            .build()
            .globalOperationParameters(this.operationParameters());
}

2.3 SecurityConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().and().csrf().disable()
                .authorizeRequests()
                // Swagger2
                .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs", "/webjars/springfox-swagger-ui/**").permitAll()
                // 其他所有请求需要身份认证
                .anyRequest().authenticated()
                .and()
                .logout().permitAll();
        // 开启登录认证流程过滤器
        httpSecurity.addFilterBefore(new JwtLoginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
        // 访问控制时登录状态检查过滤器
        httpSecurity.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers( "/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs", "/webjars/springfox-swagger-ui/**");
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枫以 2022-09-18 19:29:24

问题已解决。
代理的问题,使用 CGLIB 代理即可,如下:

@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true, proxyTargetClass = true)

参考:https://stackoverflow.com/que...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文