springboot + spring security + swagger 整合

springboot整合 spring security 和swagger-ui :

 

pom.xml文件中添加相关依赖:

        
        
            org.springframework.boot
            spring-boot-starter-security
        

        
            io.springfox
            springfox-swagger2
            2.9.2
        
        
            io.springfox
            springfox-swagger-ui
            2.9.2
        

启动类中添加Swagger2启动注解

@SpringBootApplication
@EnableSwagger2
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

接着随便写两个接口:一个是根路径一个是在/security 路径

/**
 * @Author:lht
 * @Date: 2020/5/21
 * @Desc:
 **/
@RestController
@Api(description = "test")
public class Test {

    @GetMapping("/")
    @ApiOperation(value = "test",notes = "test")
    public String test(){
        return "success!";
    }

    @GetMapping("/security")
    @ApiOperation(value = "hello",notes = "hello")
    public String security(){
        return "hello springboot security!";
    }

}

启动项目,访问 localhost:port/swagger-ui.html 页面直接跳转到如下页面:

springboot + spring security + swagger 整合_第1张图片

这是因为springboot项目整合spring security时,swagger-ui 页面的请求会被spring security拦截,然后自动跳转到spring security 登录界面。

在实际的项目中我们会为接口配置权限,哪些需要过滤拦截,那些可以直接访问,我们只需要在spring security中进行配置即可:

/**
 * @Author:lht
 * @Date: 2020/5/21
 * @Desc:
 **/
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    //静态资源配置
    @Override
    public void configure(WebSecurity web) throws Exception {
        //swagger2所需要用到的静态资源,允许访问
        web.ignoring().antMatchers("/v2/api-docs",
                "/swagger-resources/configuration/ui",
                "/swagger-resources",
                "/swagger-resources/configuration/security",
                "/swagger-ui.html");
    }
    
    //url 配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //允许根路径url的访问
                .antMatchers("/").permitAll()
                //允许swagger-ui.html访问
                .antMatchers("/swagger-ui.html").permitAll()
                .anyRequest().authenticated()
                .and()
                .logout().permitAll()
                .and()
                .formLogin().permitAll();
    }


}

这里关键在于继承了

WebSecurityConfigurerAdapter类,并实现了它的configure接口,自定义了拦截规则。我们启动一下看看效果:我们看到swagger界面可正常访问了。

springboot + spring security + swagger 整合_第2张图片

接着看一下接口权限配置是否成功,我们在上面配置看了 / 即根路径和/swagger-ui.html 路径是允许访问的,其他路径均会被spring security拦截,测试结果:

根路径访问成功

springboot + spring security + swagger 整合_第3张图片

/security 返回了一个HTML页面:其实是spring security的登录界面

springboot + spring security + swagger 整合_第4张图片

你可能感兴趣的:(springboot入门)