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)
spring boot:swagger3的安全配置(swagger 3.0.0 / spring security / spring boot 2.3.3)的更多相关文章
- 006-Spring Boot自动配置-Condition、Conditional、Spring提供的Conditional自动配置
一.接口Condition.Conditional(原理) 主要提供一下方法 boolean matches(ConditionContext context, AnnotatedTypeMetada ...
- spring多个定时任务quartz配置
spring多个定时任务quartz配置 <?xml version=”1.0″ encoding=”UTF-8″?> <beans xmlns=”http://www.spring ...
- spring boot:swagger3文档展示分页和分栏的列表数据(swagger 3.0.0 / spring boot 2.3.3)
一,什么情况下需要展示分页和分栏的数据的文档? 分页时,页面上展示的是同一类型的列表的数据,如图: 分栏时,每行都是一个列表,而且展示的数据类型也可能不同 这也是两种常用的数据返回形式 说明:刘宏缔的 ...
- spring boot:用swagger3生成接口文档,支持全局通用参数(swagger 3.0.0 / spring boot 2.3.2)
一,什么是swagger? 1, Swagger 是一个规范和完整的文档框架, 用于生成.描述.调用和可视化 RESTful 风格的 Web 服务文档 官方网站: https://swagger.i ...
- Spring Boot使用MyBatis Generator、Swagger
MyBatis是Java目前主流的ORM框架,在Spring Boot中使用MyBatis可以参考这篇文章:http://www.ityouknow.com/springboot/2016/11/06 ...
- 学记:为spring boot写一个自动配置
spring boot遵循"约定优于配置"的原则,使用annotation对一些常规的配置项做默认配置,减少或不使用xml配置,让你的项目快速运行起来.spring boot的神奇 ...
- Spring Boot 部署与服务配置
Spring Boot 其默认是集成web容器的,启动方式由像普通Java程序一样,main函数入口启动.其内置Tomcat容器或Jetty容器,具体由配置来决定(默认Tomcat).当然你也可以将项 ...
- Spring Boot 探索系列 - 自动化配置篇
26. Logging Prev Part IV. Spring Boot features Next 26. Logging Spring Boot uses Commons Logging f ...
- Spring Boot Dubbo applications.properties 配置清单
摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 与其纠结,不如行动学习.Innovate ,And out execute ! 』 本文 ...
随机推荐
- 嵌入式Linux软链接使用技巧
软链接概述 软链接是Linux下常用的一种共享文件方式.目录的方式,这种方式类似于Windows下的快捷方式.一般一个文件或者目录在不同的路径都需要的时候,可以通过创建软链接的方式来共享,这样只系统下 ...
- Combine 框架,从0到1 —— 4.在 Combine 中使用计时器
本文首发于 Ficow Shen's Blog,原文地址: Combine 框架,从0到1 -- 4.在 Combine 中使用计时器. 内容概览 前言 使用计时器执行周期性的工作 将计时器转换为计时 ...
- 学会使用BeanUtils,提高你的开发效率
一.关于BeanUtils 一说到BeanUtils,大家可能不清楚指的哪个BeanUtils.因为它在很多包里面都有,其中挺常用的就是 (1)org.apache.commons.beanutils ...
- Java枚举解读
Java枚举 枚举类概念的理解与定义 一个类的对象是有限个,确定的,我们称此为枚举类. 当需要定义和维护一组常量时,强烈建议使用枚举类. 如果一个枚举类中只有一个对象,则可以作为单例模式的实现方式. ...
- JVM直接内存(Direct Memory)
直接内存 1.直接内存不是虚拟机运行时数据区的一部分,也不是<Java虚拟机规范>中定义的内存区域. 2.直接内存是Java堆外的.直接向系统申请的内存区间. 3.简单理解: java p ...
- Netty之ChannelOption的各种参数
ChannelOption.SO_BACKLOG, 1024 BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,用于临时存放已完成三次握手的请求的队列的最 ...
- netty字节分包
高并发压测时,发现来自网关的消息出现粘包现象:分包就是势在必行的 前置和处理平台(暂时)使用netty通话,由于都是服务器平台使用DelimiterBasedFrameDecoder来解决分包 和网关 ...
- zookeeper 回调和Watcher
ZooKeeper客户端可以对指定节点设置指定Watcher,当服务器指定节点发生变化是,客户端会收到服务器的通知,然后客户端可以执行相应Watcher的代码. 默认ZooKeeper内置了一个wat ...
- NLP常见任务
借助BERT论文, 梳理下自然语言处理当前常见的任务. NLP任务 根据判断主题的级别, 将所有的NLP任务分为两种类型: token-level task: token级别的任务. 如完形填空(Cl ...
- spring:spring再总结(ioc、aop、DI等)
IOC(Inversion of Control),即"控制反转",不是一种技术而是一种思想 1.IOC的理解 Ioc意味着将你设计好的对象交给容器控制,而不是传统的在你的对象内部 ...