springboot Swagger2集成和使用

说明

     我们在开发rest 接口时,肯定需要调试,然后自己需要额外安装 如postman等工具,还要自己写脚本数据进行调试,也不方便管理。所幸 springboot有提供 swagger插件功能。
和别的技术教程区别是,我配置的是 maven打包为jar文件和使用security框架进行鉴权的情况下的配置:

首先:
    我们引入需要的maven依赖:

        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.boot
            spring-boot-starter-security
        
        
        
            io.springfox
            springfox-swagger2
            2.7.0
        
        
            io.springfox
            springfox-swagger-ui
            2.7.0
        

采用bean注册的方式进行swagger的配置。

@Configuration
@EnableSwagger2
@Profile({"local","dev"})//只有这些环境才可以用
public class SwaggerConfig {

    @Value("${spring.application.name}")
    private String projectName;
    /**
     * 全局参数
     * 增加 header 头的一个参数 Authorization 用于校验api
     *
     * @return
     */
    private List parameter() {
        List params = new ArrayList<>();
        params.add(new ParameterBuilder().name("Authorization")
                .description("通过用户密码获取授权token,--header 'Authorization:$token'")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .defaultValue("")
                .required(false).build());
        return params;
    }


    @Bean
    public Docket sysApi() {
        String pkname = new SwaggerConfig().getClass().getPackage().getName();
        //配置需要被api扫描的包路径,只会显示该包下的api
        pkname = pkname.substring(0,pkname.lastIndexOf("."))+".controller";
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(pkname))
                .paths(PathSelectors.any())
                .build().globalOperationParameters(parameter());
                //.securitySchemes(newArrayList(oauth()))
               // .securityContexts(newArrayList(securityContext()));
    }

    /**
    * info
    *  配置api视图显示的信息
    * @param
    * @return
    * @throws
    */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(projectName+" API DEBUG")
//                .description(" api 调试")
                .termsOfServiceUrl("")
//                .contact("shengshengsheng")
                .version("1.0")
                .build();
    }

}

因为是jar方式运行服务,静态页面会找不到路径,然后配置:

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/META-INF/resources/webjars/");

        super.addResourceHandlers(registry);
    }
}

因为加了security的配置,我们需要排除一些路径的鉴权

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //1. 依靠用户标识危害网站,2. 利用网站对用户标识的信任,欺骗用户的浏览器发送HTTP请求给目标站点,可以通过IMG标签会触发一个GET请求,可以利用它来实现CSRF攻击
    //防御CSRF(跨站请求伪造)可以通过动态token验证的方式来实现,每次请求生成一个动态token给前端,前端在后续的请求中附加该token,如果token不存在或不正确说明不是正常请求,予以屏蔽,从而达到解决CSRF问题的目的// @formatter:off
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable() //禁用跨站请求伪造功能
                .authorizeRequests()
                .antMatchers(
                        "/info",
                        "/api",
                        "/v2/api-docs",
                        "/swagger-resources/**",
                        "/swagger-ui.html**",
                        "/webjars/**",
                        "/medical-provider/api-docs",
                        "/static/**",
                        "/druid/**",
                        "/error/**"
                ).permitAll()
                .antMatchers("/**").authenticated();

    }
}

然后做一下路由跳转:

/**
    *  跳转api调试页面
    * @param
    * @return
    * @throws
    */
    @RequestMapping("/api")
    public String api() {
        return "redirect:/swagger-ui.html";
    }

就可以愉快的进行访问了。
访问路径 : http://localhost:8080/api

更多,请关注:
springboot 技术实践总结

你可能感兴趣的:(springboot Swagger2集成和使用)