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
對應的原始碼可以訪問這裡獲取:
說明:作者:劉巨集締 郵箱: [email protected]
二,演示專案的相關資訊
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/", "[email protected]")) .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)