SpringBoot+Spring Security+ JWT 集成Swagger文档踩坑记录

本文详细介绍了如何在SpringSecurity安全框架下成功集成Swagger,包括引入依赖、配置Swagger以及在SpringSecurity中放开Swagger资源请求的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 前言

由于权限框架对所有的请求都进行了拦截,发现Swagger页面的jss和css都被拦截了,这样就需要对Swagger所有的资源请求路径放开

  • 解决办法

一、首先要引入对应的Swagger依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

二、添加一下对应的Swagger配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(true)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.gsww.zwfwsx.controller"))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("zwfwsx-Api")
                .description("zwfwsx Api")
                .version("0.0.1")
                .build();
    }
}

三、然而Spring Security集成Swagger后上面这2步是不能成功的,还是资源请求会被拦截,要在你的Spring Security的配置类里面加入对资源请求的放开

httpSecurity.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
             .and().authorizeRequests()
             // 所有/trace/user/ 的所有请求 都放行
             .antMatchers("/trace/users/**").permitAll()
             // swagger start
             .antMatchers("/swagger-ui.html").permitAll()
             .antMatchers("/swagger-resources/**").permitAll()
             .antMatchers("/images/**").permitAll()
             .antMatchers("/webjars/**").permitAll()
             .antMatchers("/v2/api-docs").permitAll()
             .antMatchers("/configuration/ui").permitAll()
             .antMatchers("/configuration/security").permitAll()
             // swagger end
             // 所有请求都需要认证
             .anyRequest().authenticated();
     httpSecurity.headers().cacheControl();
     httpSecurity.csrf().disable();
     httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值