spring boot:swagger3的安全配置(swagger 3.0.0 / spring security / spring boot 2.3.3)


一,swagger有哪些環節需要注意安全?

1,生產環境中,要關閉swagger

   application.properties中配置:

  springfox.documentation.swagger-ui.enabled=false

 

2,swagger使用一台專用的服務器來部署,

   可以訪問的ip地址要做限制,

   外部的防火牆和應用中都做限制,

 

3,自定義訪問swagger的url

 

 4, 可以訪問swagger的用戶要做權限的驗證

 

說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest

         對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/

說明:作者:劉宏締 郵箱: 371125307@qq.com

 

二,演示項目的相關信息

1,項目地址

https://github.com/liuhongdi/swagger3security

 

2,項目功能說明:

     演示了swagger3的安全配置

 

3,項目結構:如圖:

三,配置文件說明

1,pom.xml

        <!-- swagger3 begin -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!-- spring security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

 

2,application.properties

#error
server.error.include-stacktrace=always
#error
logging.level.org.springframework.web=trace
#swagger,使可用
springfox.documentation.swagger-ui.enabled=true
#改變url
springfox.documentation.swagger-ui.base-url=/lhddoc
#設置允許訪問的ip地址白名單
swagger.access.iplist = 192.168.3.1,127.0.0.1

 

四,java代碼說明

1,Swagger3Config.java

@EnableOpenApi
@Configuration
public class Swagger3Config implements WebMvcConfigurer {

    @Bean
    public Docket createRestApi() {
        //返回文檔摘要信息
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class))
                .paths(PathSelectors.any())
                .build()
                .globalRequestParameters(getGlobalRequestParameters())
                .globalResponses(HttpMethod.GET, getGlobalResonseMessage())
                .globalResponses(HttpMethod.POST, getGlobalResonseMessage());
    }

    //生成接口信息,包括標題、聯系人等
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3接口文檔")
                .description("如有疑問,請聯系開發工程師老劉。")
                .contact(new Contact("劉宏締", "https://www.cnblogs.com/architectforest/", "371125307@qq.com"))
                .version("1.0")
                .build();
    }

    //生成全局通用參數
    private List<RequestParameter> getGlobalRequestParameters() {
        List<RequestParameter> parameters = new ArrayList<>();
        parameters.add(new RequestParameterBuilder()
                .name("appid")
                .description("平台id")
                .required(true)
                .in(ParameterType.QUERY)
                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                .required(false)
                .build());
        parameters.add(new RequestParameterBuilder()
                .name("udid")
                .description("設備的唯一id")
                .required(true)
                .in(ParameterType.QUERY)
                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                .required(false)
                .build());
        parameters.add(new RequestParameterBuilder()
                .name("version")
                .description("客戶端的版本號")
                .required(true)
                .in(ParameterType.QUERY)
                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                .required(false)
                .build());
         return parameters;
    }

    //生成通用響應信息
    private List<Response> getGlobalResonseMessage() {
        List<Response> responseList = new ArrayList<>();
        responseList.add(new ResponseBuilder().code("404").description("找不到資源").build());
         return responseList;
    }
}

配置swagger3

 

2,HomeController.java

@Api(tags = "首頁信息管理")
@Controller
@RequestMapping("/home")
public class HomeController {

    @Operation(summary = "session詳情")
    @GetMapping("/session")
    @ResponseBody
    public String session() {
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
        Enumeration e   =   session.getAttributeNames();
        String s = "";
        while( e.hasMoreElements())   {
            String sessionName=(String)e.nextElement();
            s += "name="+sessionName+";<br/>";
            s += "value="+session.getAttribute(sessionName)+";";
        }
        return s;
    }

}

查看當前登錄用戶的session

 

3,SecurityConfig.java

@Configuration
@EnableWebSecurity
 public class SecurityConfig extends WebSecurityConfigurerAdapter {

     @Value("${swagger.access.iplist}")
     private String iplist;

     @Override
     protected void configure(HttpSecurity http) throws Exception {
                 //得到iplist列表
                String iprule = "";
                //hasIpAddress('10.0.0.0/16') or hasIpAddress('127.0.0.1/32')
                String[] splitAddress=iplist.split(",");
                for(String ip : splitAddress){
                     if (iprule.equals("")) {
                         iprule = "hasIpAddress('"+ip+"')";
                     } else {
                         iprule += " or hasIpAddress('"+ip+"')";
                     }
                }
                String swaggerrule = "hasAnyRole('ADMIN','DEV') and ("+iprule+")";

                  //login和logout
                  http.formLogin()
                         .defaultSuccessUrl("/home/session")
                        .failureUrl("/login-error.html")
                        .permitAll()
                       .and()
                       .logout();

                  //匹配的頁面,符合限制才可訪問
                  http.authorizeRequests()
                  //.antMatchers("/actuator/**").hasIpAddress("127.0.0.1")
                  //.antMatchers("/admin/**").access("hasRole('admin') and (hasIpAddress('127.0.0.1') or 
//hasIpAddress('192.168.1.0/24') or hasIpAddress('0:0:0:0:0:0:0:1'))");
.antMatchers("/lhddoc/**").access(swaggerrule) .antMatchers("/goods/**").hasAnyRole("ADMIN","DEV"); //剩下的頁面,允許訪問 http.authorizeRequests().anyRequest().permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { //添加兩個賬號用來做測試 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("lhdadmin") .password(new BCryptPasswordEncoder().encode("123456")) .roles("ADMIN","USER") .and() .withUser("lhduser") .password(new BCryptPasswordEncoder().encode("123456")) .roles("USER"); } }

spring security的配置,重點是ip地址白名單的限制要加入

 

4,Goods.java等,可以從github.com查看

 

五,測試效果

1,無權限的訪問效果:

 

 用lhduser賬號登錄

從session頁面可以看到當前登錄用戶的授權角色是:ROLE_USER

 

 因為沒有權限,訪問swagger時會報錯

 

 

2,有權限訪問時的效果:

用lhdadmin登錄

 

 查看session:

 

 可以看到用戶權限包括:ROLE_ADMIN

訪問swagger:

http://127.0.0.1:8080/lhddoc/swagger-ui/

返回:

 

 

3,從非授權的ip地址訪問:

既使用獲得授權的用戶賬號登錄也會報錯,因為ip未授權

六,查看spring boot的版本

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.3.RELEASE)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM