一,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)的更多相关文章

  1. 006-Spring Boot自动配置-Condition、Conditional、Spring提供的Conditional自动配置

    一.接口Condition.Conditional(原理) 主要提供一下方法 boolean matches(ConditionContext context, AnnotatedTypeMetada ...

  2. spring多个定时任务quartz配置

    spring多个定时任务quartz配置 <?xml version=”1.0″ encoding=”UTF-8″?> <beans xmlns=”http://www.spring ...

  3. spring boot:swagger3文档展示分页和分栏的列表数据(swagger 3.0.0 / spring boot 2.3.3)

    一,什么情况下需要展示分页和分栏的数据的文档? 分页时,页面上展示的是同一类型的列表的数据,如图: 分栏时,每行都是一个列表,而且展示的数据类型也可能不同 这也是两种常用的数据返回形式 说明:刘宏缔的 ...

  4. spring boot:用swagger3生成接口文档,支持全局通用参数(swagger 3.0.0 / spring boot 2.3.2)

    一,什么是swagger? 1,  Swagger 是一个规范和完整的文档框架, 用于生成.描述.调用和可视化 RESTful 风格的 Web 服务文档 官方网站: https://swagger.i ...

  5. Spring Boot使用MyBatis Generator、Swagger

    MyBatis是Java目前主流的ORM框架,在Spring Boot中使用MyBatis可以参考这篇文章:http://www.ityouknow.com/springboot/2016/11/06 ...

  6. 学记:为spring boot写一个自动配置

    spring boot遵循"约定优于配置"的原则,使用annotation对一些常规的配置项做默认配置,减少或不使用xml配置,让你的项目快速运行起来.spring boot的神奇 ...

  7. Spring Boot 部署与服务配置

    Spring Boot 其默认是集成web容器的,启动方式由像普通Java程序一样,main函数入口启动.其内置Tomcat容器或Jetty容器,具体由配置来决定(默认Tomcat).当然你也可以将项 ...

  8. Spring Boot 探索系列 - 自动化配置篇

    26. Logging Prev  Part IV. Spring Boot features  Next 26. Logging Spring Boot uses Commons Logging f ...

  9. Spring Boot Dubbo applications.properties 配置清单

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 与其纠结,不如行动学习.Innovate ,And out execute ! 』 本文 ...

随机推荐

  1. 《搭建个人Leanote云笔记本》

    体验实验室简介 阿里云开发者实验室,提供免费阿里云资源,丰富的云计算应用场景, Step by Step 完成云产品的体验 教程介绍 本教程将介绍如何搭建个人Leanote云笔记本. 场景体验 阿里云 ...

  2. 吴恩达《深度学习》-第一门课 (Neural Networks and Deep Learning)-第二周:(Basics of Neural Network programming)-课程笔记

    第二周:神经网络的编程基础 (Basics of Neural Network programming) 2.1.二分类(Binary Classification) 二分类问题的目标就是习得一个分类 ...

  3. 学习 | canvas实现图片懒加载 && 下滑底部加载

    用canvas实现图片的懒加载并且下滑到据底部60px的时候再次加载数据,模仿UC浏览器的新闻加载. 完整代码:https://github.com/dirkhe1051931999/writeBlo ...

  4. 天猫精灵对接1:outh对接

    公司的智能家居产品需要接入语音控制,目前在对接阿里语音的天猫精灵 对接天猫精灵的第一步是完成outh鉴权 https://doc-bot.tmall.com/docs/doc.htm?spm=0.76 ...

  5. 龙芯3A4000-Debian 10上常用软件记录

    所用平台 硬件:龙芯3a4000 (MIPS64el) 操作系统:Debian 10(buster)+ MATE桌面 内核版本:4.19.90 以下所有软件同样适用于x86体系结构的Linux发行版. ...

  6. HotSpot VM 中的JIT分类

    在HotSpot VM中内嵌有两个JIT编译器,分别为Client Compiler和Server Compiler,但大多数情况下我们简称为C1编译器和C2编译器.开发人员可以通过如下命令显式指定J ...

  7. 创建Vue项目及封装axios

    1. 始vue化项目 https://www.cnblogs.com/xiaonq/p/11027880.html vue init webpack deaxios # 使用脚手架创建项目 deaxi ...

  8. c#后台代码请求访问api接口

    前言:最近公司项目与外部api接口对接较多 ,写下自己的代码总结.介绍两种访问方式(HttpClient.HttpWebRequest) 一.HttpWebRequest 访问Api private ...

  9. 基础篇:深入解析JAVA泛型和Type类型体系

    目录 1 JAVA的Type类型体系 2 泛型的概念 3 泛型类和泛型方法的示例 4 类型擦除 5 参数化类型ParameterizedType 6 泛型的继承 7 泛型变量TypeVariable ...

  10. 066 01 Android 零基础入门 01 Java基础语法 08 Java方法 02 带参有返回值方法

    066 01 Android 零基础入门 01 Java基础语法 08 Java方法 04 带参有返回值方法 本文知识点:带参有返回值方法 说明:因为时间紧张,本人写博客过程中只是对知识点的关键步骤进 ...