spring和swagger

swagger本身是一个框架,可以用来设计Api,可以提供一个UI界面展示Api文档,也可以通过UI交互发送数据到服务端进行接口测试。

spring是一个java框架,众所周知。

而springfox,则将swagger集成到spring中。

springboot集成swagger2的步骤:

1.maven构建的springboot项目,在pom中引入以下两个依赖来集成swagger:

<!-- swagger -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

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

2.在Application.java同级创建Swagger2的配置类Swagger2,代码示例如下:

package com.mark;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author mark
 * @date 2019/10/27 11:50
 * @description swagger配置类
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.mark"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .description("接口文档")
                .build();
    }

}

3.controller方法上添加注解,@ApiOperation描述接口作用,@ApiImplicitParams@ApiImplicitParam标识接口入参,@ApiResponses@ApiResponse标识接口返回状态码,比如200代表成功,-1代表失败。示例代码如下:

package com.mark.web.hello;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.*;

/**
 * @author mark
 * @date 2019/10/24 20:39
 */
@RestController
public class HelloController {

    @ApiOperation(value = "Get Hello")
    @ApiImplicitParam(name = "name", value = "姓名", defaultValue = "My Friend")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Success"),
            @ApiResponse(code = -1, message = "Fail")
    })
    @GetMapping("/hello")
    public String sayHello(@RequestParam(name = "name", required = false, defaultValue = "My Friend") String name) {
        return "Hello " + name;
    }

}

4.Model属性加上注解@ApiModelProperty标识属性含义,示例代码如下:

package com.mark.domain.user;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @author guolimin.lc
 */
@Data
public class User {

    @ApiModelProperty(value = "主键")
    private Long id;

    @ApiModelProperty(value = "姓名")
    private String name;

    @ApiModelProperty(value = "年龄")
    private Integer age;

}

备注:使用swagger之后,接口返回数据一般就不再定义list或map了,而是基本上都返回model,这样做是为了swagger的文档可以正确显示接口返回数据。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 可以通过在Spring Security配置中添加以下内容来放行Swagger2: ``` @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs", "/webjars/**") .permitAll() .anyRequest() .authenticated() .and() .csrf() .disable(); } } ``` 这个配置将允许访问Swagger UI和API文档,而不需要进行身份验证。 ### 回答2: Spring Security是一个灵活的框架,可以用于构建各种类型的安全的应用程序。它可以在应用程序中实现身份验证和授权,并确保Web应用程序的安全性。Swagger是一种API文档规范和工具,用于描述Web服务的结构和功能。Swagger为Web服务的用户提供交互式和完整的文档,因此在实现API的时候会用到SwaggerSpring Security默认情况下会保护应用程序中的所有URI。但是,有时候我们需要放行Swagger的相关路径,这时候我们需要对Spring Security进行配置。 首先,配置Swagger的相关依赖项。在pom.xml中添加以下依赖: ```xml <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.5.2</version> </dependency> ``` 接下来,需要在Spring Security中启用跨域资源共享(CORS)。CORS必须启用,否则将无法通过Swagger UI访问REST API。在WebSecurityConfigurerAdapter类中重写configure(HttpSecurity http)方法并添加以下代码: ```java http.cors().and().csrf().disable(); ``` 还需要更新Swagger的默认配置,以包括与Spring Security的整合。我们可以在AppConfig类中添加以下配置: ```java @Configuration @EnableSwagger2 public class SwaggerConfig implements WebMvcConfigurer { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .securitySchemes(Arrays.asList(apiKey())) .securityContexts(Arrays.asList(securityContext())); } private ApiKey apiKey() { return new ApiKey("JWT", AUTHORIZATION_HEADER, "header"); } private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.any()) .build(); } List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; return Arrays.asList(new SecurityReference("JWT", authorizationScopes)); } } ``` 这里,我们将API文档令牌设置为JWT并将其添加到默认的安全上下文中。接下来,我们可以将匹配所有Swagger UI路径的请求放行,以允许用户在UI中访问API文档。在WebSecurityConfigurerAdapter类中添加以下配置: ```java @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**"); } ``` 以上代码将Spring Security配置为忽略Swagger的所有路径。这样做后,Swagger UI就可以在应用程序中使用了。 总之,要放行Swagger2,首先需要在pom.xml中添加Swagger相关依赖项,然后在Spring Security中启用CORS,更新Swagger的默认配置并将所有Swagger UI路径请求放行。这样就可以在应用程序中使用Swagger UI了。 ### 回答3: 在使用Spring Security进行权限控制的时候,我们可能需要对某些页面或者接口进行放行,以便于开发人员或者测试人员进行访问。在这种情况下,我们需要对Spring Security进行相应的配置,使得它能够对一些特定的URL进行放行。在此,我们可以以Swagger2为例,介绍一下如何进行配置。 首先,我们需要在Spring Boot的配置文件中进行一些基本的配置,以便于让Swagger2正常运行。我们可以在pom.xml文件中加入如下依赖: ``` <dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.9.3.RELEASE</version> </dependency> ``` 然后,在Spring Boot的配置文件中加入如下配置: ``` swagger.enabled=true #启用swagger swagger.basePackage=com.example.swaggerdemo.controller #扫描的接口所在的包 swagger.title=swagger demo #文档标题 swagger.description=swagger demo API #文档描述 swagger.version=1.0.0 #文档版本号 ``` 接下来,我们需要配置Spring Security,使得它能够对Swagger2进行放行。我们可以在WebSecurityConfigurerAdapter的子类中进行如下配置: ``` @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() //放行Swagger2的接口 .antMatchers("/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/v2/**", "/configuration/**") .permitAll() .anyRequest() .authenticated() .and() .formLogin() .permitAll() .and() .logout() .permitAll(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/swagger-resources/**", "/webjars/**"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService); } } ``` 在这里,我们配置了对Swagger2的接口进行放行,使得它们可以被任何人正常访问。同时,我们还需要配置忽略Swagger2的一些资源文件,以避免出现权限问题。最后,我们还需要对Spring Security进行基本的认证授权配置,这些配置可以根据具体的业务需求进行相应的修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值