├── .gitignore ├── .idea ├── .gitignore ├── Spring-Boot-Notes.iml ├── misc.xml ├── modules.xml └── vcs.xml ├── README.md ├── activiti ├── activiti │ ├── .gitignore │ ├── .mvn │ │ └── wrapper │ │ │ ├── maven-wrapper.jar │ │ │ └── maven-wrapper.properties │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── wj │ │ │ └── activiti │ │ │ ├── ActivitiApplication.java │ │ │ ├── configration │ │ │ └── SecurityConfig.java │ │ │ ├── controller │ │ │ ├── ActivitiController.java │ │ │ └── UserController.java │ │ │ ├── entity │ │ │ ├── Permission.java │ │ │ ├── ResponseResult.java │ │ │ ├── Role.java │ │ │ └── User.java │ │ │ ├── reposity │ │ │ ├── PermissionMapper.java │ │ │ └── UserMapper.java │ │ │ └── service │ │ │ ├── UserService.java │ │ │ └── UserServiceImpl.java │ │ └── resources │ │ ├── application.yml │ │ ├── default-project.json │ │ └── processes │ │ ├── leaveApplication.bpmn20.xml │ │ └── myEvection.bpmn20.xml └── activiti_demo │ ├── pom.xml │ └── src │ ├── main │ └── resources │ │ ├── activiti.cfg.xml │ │ ├── bpmn │ │ └── leaveApplication.bpmn20.xml │ │ └── log4j2.xml │ └── test │ └── java │ └── com │ └── wj │ └── activiti │ ├── TestCreat.java │ └── TestLeaveApplication.java ├── demo ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── shumile │ │ │ └── demo │ │ │ ├── DemoApplication.java │ │ │ └── HelloController.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── shumile │ └── demo │ └── DemoApplicationTests.java ├── druid_demo ├── .gitignore ├── .idea │ ├── misc.xml │ ├── modules.xml │ └── vcs.xml ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── shumile │ │ │ └── druid_demo │ │ │ ├── DruidDemoApplication.java │ │ │ ├── User.java │ │ │ ├── UserDao.java │ │ │ └── filter │ │ │ └── ConnectionLogFilter.java │ └── resources │ │ ├── META-INF │ │ └── druid-filter.properties │ │ └── application.properties │ └── test │ └── java │ └── com │ └── shumile │ └── druid_demo │ └── DruidDemoApplicationTests.java ├── hystrix_demo ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── shumile │ │ │ └── hystrix_demo │ │ │ └── HystrixDemoApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── shumile │ └── hystrix_demo │ └── HystrixDemoApplicationTests.java ├── jwt_demo ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── wj │ │ └── jwt │ │ ├── JwtApplication.java │ │ ├── annotation │ │ └── IgnoreToken.java │ │ ├── config │ │ └── WebMvcConfig.java │ │ ├── controller │ │ ├── LoginController.java │ │ └── UserController.java │ │ ├── entity │ │ └── User.java │ │ ├── handler │ │ └── AuthorisationInterceptor.java │ │ ├── reposity │ │ └── UserMapper.java │ │ ├── service │ │ ├── JwtService.java │ │ ├── UserService.java │ │ └── UserServiceImpl.java │ │ ├── util │ │ └── MD5Util.java │ │ └── vo │ │ ├── ResponseResult.java │ │ └── UserVo.java │ └── resources │ └── application.yml ├── mybatis_demo2 ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── shumile │ │ │ └── mybatis_demo2 │ │ │ └── MybatisDemo2Application.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── shumile │ └── mybatis_demo2 │ └── MybatisDemo2ApplicationTests.java ├── spring-boot-jpa ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── out │ └── production │ │ └── .mvn │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── shumile │ │ │ └── springbootjpa │ │ │ ├── SpringBootJpaApplication.java │ │ │ ├── Test.java │ │ │ ├── User.java │ │ │ └── UserRepository.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── shumile │ └── springbootjpa │ └── SpringBootJpaApplicationTests.java ├── spring-boot-mybatis ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── shumile │ │ │ └── springbootmybatis │ │ │ ├── SpringBootMybatisApplication.java │ │ │ ├── User.java │ │ │ └── mapper │ │ │ ├── UserBuilder.java │ │ │ ├── UserMapperWithAnnotation.java │ │ │ ├── UserMapperWithBuilder.java │ │ │ └── UserMapperWithXml.java │ └── resources │ │ ├── application.properties │ │ ├── mapper │ │ └── UserMapper.xml │ │ └── mybatis-configuration.xml │ └── test │ └── java │ └── com │ └── shumile │ └── springbootmybatis │ └── SpringBootMybatisApplicationTests.java ├── spring-boot-mybatisCache ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── shumile │ │ │ └── springbootmybatis │ │ │ ├── SpringBootMybatisApplication.java │ │ │ ├── User.java │ │ │ └── mapper │ │ │ ├── UserMapper.java │ │ │ └── UserMapperWithAnnotation.java │ └── resources │ │ ├── application.properties │ │ ├── mapper │ │ └── UserMapper.xml │ │ └── mybatis-configuration.xml │ └── test │ └── java │ └── com │ └── shumile │ └── springbootmybatis │ └── SpringBootMybatisApplicationTests.java ├── springSecurity ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── pom.xml ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── wj │ │ │ │ └── springSecurity │ │ │ │ ├── SpringsecurityOathu2Application.java │ │ │ │ ├── config │ │ │ │ ├── SecurityConfig.java │ │ │ │ └── WebSecurityConfig.java │ │ │ │ ├── controller │ │ │ │ └── UserController.java │ │ │ │ ├── entity │ │ │ │ ├── Permission.java │ │ │ │ ├── Role.java │ │ │ │ └── User.java │ │ │ │ ├── reposity │ │ │ │ ├── PermissionMapper.java │ │ │ │ └── UserMapper.java │ │ │ │ └── service │ │ │ │ ├── UserService.java │ │ │ │ └── UserServiceImpl.java │ │ └── resources │ │ │ └── application.yml │ └── test │ │ └── java │ │ └── com │ │ └── wj │ │ └── springSecurity │ │ └── SpringsecurityOathu2ApplicationTests.java └── table_and_data.sql ├── springSecurityJwt ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── pom.xml ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── wj │ │ │ │ └── springSecurity │ │ │ │ └── jwt │ │ │ │ ├── SpringsecurityJwtApplication.java │ │ │ │ ├── config │ │ │ │ └── SecurityConfig.java │ │ │ │ ├── controller │ │ │ │ ├── JwtAuthenticationController.java │ │ │ │ └── UserController.java │ │ │ │ ├── entity │ │ │ │ ├── Permission.java │ │ │ │ ├── Role.java │ │ │ │ └── User.java │ │ │ │ ├── filter │ │ │ │ └── JwtAuthenticationFilter.java │ │ │ │ ├── reposity │ │ │ │ ├── PermissionMapper.java │ │ │ │ └── UserMapper.java │ │ │ │ ├── service │ │ │ │ ├── JwtService.java │ │ │ │ ├── UserService.java │ │ │ │ └── UserServiceImpl.java │ │ │ │ ├── utils │ │ │ │ └── MD5Util.java │ │ │ │ └── vo │ │ │ │ ├── ResponseResult.java │ │ │ │ └── UserVo.java │ │ └── resources │ │ │ └── application.yml │ └── test │ │ └── java │ │ └── com │ │ └── wj │ │ └── springSecurity │ │ └── SpringsecurityOathu2ApplicationTests.java └── table_and_data.sql ├── spring_OAthu2 ├── resource_server │ ├── .gitignore │ ├── .mvn │ │ └── wrapper │ │ │ ├── maven-wrapper.jar │ │ │ └── maven-wrapper.properties │ ├── pom.xml │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── wj │ │ │ │ └── resource_server │ │ │ │ ├── ResourceServerApplication.java │ │ │ │ ├── config │ │ │ │ └── ResourceConfig.java │ │ │ │ └── controller │ │ │ │ └── ResourceController.java │ │ └── resources │ │ │ └── application.yml │ │ └── test │ │ └── java │ │ └── com │ │ └── wj │ │ └── resource_server │ │ └── ResourceServerApplicationTests.java └── springSecurityOathu2 │ ├── .gitignore │ ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties │ ├── pom.xml │ └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── wj │ │ │ └── springSecurityOathu2 │ │ │ ├── SpringsecurityOathu2Application.java │ │ │ ├── config │ │ │ ├── AuthorityConfig.java │ │ │ ├── SecurityConfig.java │ │ │ └── WebSecurityConfig.java │ │ │ ├── controller │ │ │ └── UserController.java │ │ │ ├── entity │ │ │ ├── Permission.java │ │ │ ├── Role.java │ │ │ └── User.java │ │ │ ├── reposity │ │ │ ├── PermissionMapper.java │ │ │ └── UserMapper.java │ │ │ └── service │ │ │ ├── UserService.java │ │ │ └── UserServiceImpl.java │ └── resources │ │ ├── application.yml │ │ └── oauth_client_details.sql │ └── test │ └── java │ └── com │ └── wj │ └── springSecurityOathu2 │ └── SpringsecurityOathu2ApplicationTests.java └── spring_jdbc ├── .gitignore ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── shumile │ │ └── spring_jdbc │ │ ├── SpringJdbcApplication.java │ │ ├── User.java │ │ └── UserDao.java └── resources │ └── application.properties └── test └── java └── com └── shumile └── spring_jdbc └── SpringJdbcApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml -------------------------------------------------------------------------------- /.idea/Spring-Boot-Notes.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring-Boot-Notes 2 | Spring Boot 实战系列代码 3 | 4 | 来源于 【青梅主码】微信公众号文章 5 | AI 导航网推荐:aiopenminds.com/ 6 | 7 | 1、[demo](/demo):[Spring Boot的第一个项目](https://mp.weixin.qq.com/s?__biz=MzIwMTY3NjY3MA==&mid=2247483751&idx=1&sn=90bb32f21dbfd6793b899ac4cb04d52f&chksm=96eb0376a19c8a60eb9ea0b8227b3e34d55efb0feb6e1aa944d90514333f2be70635b8bc820c&token=1724332241&lang=zh_CN#rd) 8 | 9 | 2、[spring-jdbc](/spring_jdbc):[Spring Boot(三): 操作数据库-Spring JDBC](https://mp.weixin.qq.com/s?__biz=MzIwMTY3NjY3MA==&mid=2247483779&idx=1&sn=6ce5bbd2d8028b176ecf3b1b7fa8f3ea&chksm=96eb0392a19c8a84f1e7356a36012a2ef2f17f4d70f60c83ea42c1e72ed5a561c18d1782577e&token=1724332241&lang=zh_CN#rd) 10 | 11 | 3、[spring-boot-jpa](/spring-boot-jpa):[Spring Boot(四):让人又爱又恨的JPA](https://mp.weixin.qq.com/s?__biz=MzIwMTY3NjY3MA==&mid=2247483799&idx=1&sn=f0a553daf412aefeb2f7877970b04aca&chksm=96eb0386a19c8a90c15b1dae13d39546a2d01875d3f3489c2e2f709a97f8f8ca87bee4ec58e0&token=1724332241&lang=zh_CN#rd) 12 | 13 | 4、[spring-boot-mybatis](/spring-boot-mybatis):[Spring Boot(五):春眠不觉晓,Mybatis知多少](https://mp.weixin.qq.com/s?__biz=MzIwMTY3NjY3MA==&mid=2247483821&idx=1&sn=7c5ed87610b93589266106d1b07191d1&chksm=96eb03bca19c8aaa5967520fe03381481020450834e7b4e518dd729dc38b71c4cb50154d7e8d&token=1724332241&lang=zh_CN#rd) 14 | 15 | 5、[spring-boot-Security](/springSecurity):[Spring Boot(十一):Spring Security 实现权限控制](https://mp.weixin.qq.com/s?__biz=MzIwMTY3NjY3MA==&mid=2247485765&idx=1&sn=53a386cd11a713a71282efc5c0aba4f9&chksm=96eb0b54a19c82426f19af90206c3c8828a17a3911f0de8af1c96990cd2920588905b3cc8b46&token=2005006674&lang=zh_CN#rd) 16 | 17 | 6、[spring_OAthu2](/spring_OAthu2):[Spring Boot(十二):陌生又熟悉的 OAuth2.0 协议,实际上每个人都在用](https://mp.weixin.qq.com/s?__biz=MzIwMTY3NjY3MA==&mid=2247485836&idx=1&sn=26aed3b90036910c81d9afebec53412d&chksm=96eb0b9da19c828bf5dc7162c5d2abd3a823cf5f33ed104b07ac9e33bf53e57cd1b8eb265c41&token=1724332241&lang=zh_CN#rd) 18 | 19 | 7、[Activit](/activiti/activiti_demo/):[Activiti工作流(一):OA 上的那些请假流程如何快速实现呢?](https://mp.weixin.qq.com/s?__biz=MzIwMTY3NjY3MA==&mid=2247485895&idx=1&sn=9657ea5abb80d21242dd8a13d7bcaef0&chksm=96eb0bd6a19c82c02a559a8a019aa44e4e66e20b476d5f4ed216f119c17b443126efd887ed46&token=1724332241&lang=zh_CN#rd) 20 | 21 | 8、[Spring-Boot-Activit](/activiti/activiti/):[Spring Boot(十三):Spring Boot 集成 Activiti - 快速实现工作流 22 | ](https://mp.weixin.qq.com/s?__biz=MzIwMTY3NjY3MA==&mid=2247486433&idx=1&sn=09b3fe0358d59718b101b7503d3c7dcf&chksm=96eb09f0a19c80e69d52976922aa0537d77512f855e3d925477b1abd6c706fa4aea68a53c89e&token=1724332241&lang=zh_CN#rd) 23 | 24 | 9、[Spring-Boot-Activit](/jwt_demo):[告别 session,还是这个认证方案优秀! 25 | ](https://juejin.cn/post/7128212823892557861) 26 | 27 | 10、[Spring-Boot-Activit](/springSecurityJwt):[Spring Boot(十四):Spring Security JWT -实现分布式架构的认证! 28 | ](https://mp.weixin.qq.com/s?__biz=MzIwMTY3NjY3MA==&mid=2247486759&idx=1&sn=e464a886ad348bc56ee6cbc17551c02c&chksm=96eb0f36a19c86208cbcbd55b439eb26ea6501aff02bf6cdfbafbdbe8e8fa8540cdf4cc50637&token=1371809950&lang=zh_CN#rd) 29 | 30 | -------------------------------------------------------------------------------- /activiti/activiti/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /activiti/activiti/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/activiti/activiti/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /activiti/activiti/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.5/apache-maven-3.8.5-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 3 | -------------------------------------------------------------------------------- /activiti/activiti/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.0 9 | 10 | 11 | com.wj 12 | activiti 13 | 0.0.1-SNAPSHOT 14 | activiti 15 | activiti Demo project for Spring Boot 16 | 17 | 1.8 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | org.activiti 26 | activiti-spring-boot-starter 27 | 7.1.0.M6 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-security 33 | 34 | 35 | mysql 36 | mysql-connector-java 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-jdbc 42 | 2.7.0 43 | 44 | 45 | 46 | tk.mybatis 47 | mapper-spring-boot-starter 48 | 2.1.5 49 | 50 | 51 | org.projectlombok 52 | lombok 53 | true 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-starter-test 58 | 59 | 60 | junit 61 | junit 62 | 4.12 63 | test 64 | 65 | 66 | 67 | 68 | 69 | 70 | org.springframework.boot 71 | spring-boot-maven-plugin 72 | 73 | 74 | 75 | org.projectlombok 76 | lombok 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/java/com/wj/activiti/ActivitiApplication.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import tk.mybatis.spring.annotation.MapperScan; 6 | 7 | @SpringBootApplication 8 | @MapperScan("com.wj.activiti.reposity") 9 | public class ActivitiApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(ActivitiApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/java/com/wj/activiti/configration/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti.configration; 2 | import com.wj.activiti.entity.Permission; 3 | import com.wj.activiti.reposity.PermissionMapper; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 8 | import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; 9 | import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; 10 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 11 | import org.springframework.security.crypto.password.PasswordEncoder; 12 | import org.springframework.security.web.SecurityFilterChain; 13 | 14 | import javax.annotation.Resource; 15 | import java.util.List; 16 | 17 | @Configuration 18 | @Slf4j 19 | public class SecurityConfig { 20 | 21 | @Resource 22 | private PermissionMapper permissionMapper; 23 | 24 | @Bean 25 | public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 26 | ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry 27 | authorizeRequests = http.csrf().disable().authorizeRequests(); 28 | // 方式二:配置来源于数据库 29 | // 1.查询到所有的权限 30 | List allPermission = permissionMapper.findAllPermission(); 31 | // 2.分别添加权限规则 32 | allPermission.forEach((p -> { 33 | authorizeRequests.antMatchers(p.getUrl()).hasAnyAuthority(p.getName()) ; 34 | })); 35 | 36 | authorizeRequests.antMatchers("/**").fullyAuthenticated() 37 | .anyRequest().authenticated().and().formLogin(); 38 | return http.build(); 39 | } 40 | 41 | @Bean 42 | WebSecurityCustomizer webSecurityCustomizer() { 43 | return web -> { 44 | web.ignoring().antMatchers("/css/**"); 45 | web.ignoring().antMatchers("/js/**"); 46 | web.ignoring().antMatchers("/img/**"); 47 | web.ignoring().antMatchers("/plugins/**"); 48 | web.ignoring().antMatchers("/login.html"); 49 | }; 50 | } 51 | 52 | @Bean 53 | public PasswordEncoder passwordEncoder(){ 54 | return new BCryptPasswordEncoder(); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/java/com/wj/activiti/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RequestParam; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController 9 | @RequestMapping("/user") 10 | public class UserController { 11 | 12 | @GetMapping("/common") 13 | public String common() { 14 | return "hello~ common"; 15 | } 16 | 17 | @GetMapping("/admin") 18 | public String admin() { 19 | return "hello~ admin"; 20 | } 21 | 22 | @GetMapping("/test") 23 | public String test() { 24 | return "hello~ test"; 25 | } 26 | 27 | @GetMapping("/hello") 28 | public String hello(@RequestParam("code") String code) { 29 | return "hello~ 授权码 code 为:" + code; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/java/com/wj/activiti/entity/Permission.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti.entity; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Permission { 7 | private Integer id; 8 | 9 | private String url; 10 | 11 | private String name; 12 | 13 | private String description; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/java/com/wj/activiti/entity/ResponseResult.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti.entity; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | @Data 7 | @NoArgsConstructor 8 | public class ResponseResult { 9 | 10 | private Integer status; 11 | 12 | private String message; 13 | 14 | private Object data; 15 | 16 | public ResponseResult(Integer status,String message,Object data){ 17 | this(status,message); 18 | this.data = data; 19 | } 20 | 21 | public static ResponseResult getSuccessResult(Object data){ 22 | ResponseResult result = new ResponseResult(200, "成功!"); 23 | result.data = data; 24 | return result; 25 | 26 | } 27 | 28 | public ResponseResult(Integer status,String message){ 29 | this.status = status; 30 | this.message = message; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/java/com/wj/activiti/entity/Role.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti.entity; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Role { 7 | private Integer id; 8 | private String name; 9 | } 10 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/java/com/wj/activiti/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti.entity; 2 | 3 | import lombok.Data; 4 | import org.springframework.security.core.GrantedAuthority; 5 | import org.springframework.security.core.userdetails.UserDetails; 6 | 7 | import java.util.ArrayList; 8 | import java.util.Collection; 9 | import java.util.List; 10 | 11 | @Data 12 | public class User implements UserDetails { 13 | private Integer id; 14 | private String username; 15 | private String password; 16 | private String role; 17 | 18 | // 用户所有权限 19 | private List authorities = new ArrayList(); 20 | 21 | public Collection getAuthorities() { 22 | 23 | return authorities; 24 | } 25 | 26 | @Override 27 | public boolean isAccountNonExpired() { 28 | return true; 29 | } 30 | 31 | @Override 32 | public boolean isAccountNonLocked() { 33 | return true; 34 | } 35 | 36 | @Override 37 | public boolean isCredentialsNonExpired() { 38 | return true; 39 | } 40 | 41 | @Override 42 | public boolean isEnabled() { 43 | return true; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/java/com/wj/activiti/reposity/PermissionMapper.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti.reposity; 2 | 3 | import com.wj.activiti.entity.Permission; 4 | import org.apache.ibatis.annotations.Select; 5 | 6 | import java.util.List; 7 | 8 | public interface PermissionMapper { 9 | 10 | 11 | /** 12 | * 查询用户的权限根据用户查询权限 13 | * 14 | * @return 15 | */ 16 | @Select("select * from permission") 17 | List findAllPermission(); 18 | } 19 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/java/com/wj/activiti/reposity/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti.reposity; 2 | 3 | import com.wj.activiti.entity.Permission; 4 | import com.wj.activiti.entity.User; 5 | import org.apache.ibatis.annotations.Param; 6 | import org.apache.ibatis.annotations.Select; 7 | 8 | import java.util.List; 9 | 10 | public interface UserMapper { 11 | 12 | /** 13 | * 根据用户名称查询 14 | * 15 | * @param userName 16 | * @return 17 | */ 18 | @Select(" select * from user where username = #{userName}") 19 | User findByUsername(@Param("userName") String userName); 20 | 21 | /** 22 | * 查询用户的权限根据用户查询权限 23 | * 24 | * @param userName 25 | * @return 26 | */ 27 | @Select(" SELECT d.*\n" + 28 | "from user a,user_role b,role_permission c,permission d\n" + 29 | "WHERE \n" + 30 | "a.id = b.user_id\n" + 31 | "and b.role_id = c.role_id\n" + 32 | "and c.permission_id = d.id\n" + 33 | "and \n" + 34 | "a.username= #{userName};") 35 | List findPermissionByUsername(@Param("userName") String userName); 36 | } 37 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/java/com/wj/activiti/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti.service; 2 | 3 | import com.wj.activiti.entity.User; 4 | import org.springframework.security.core.userdetails.UserDetailsService; 5 | 6 | public interface UserService extends UserDetailsService { 7 | 8 | 9 | } -------------------------------------------------------------------------------- /activiti/activiti/src/main/java/com/wj/activiti/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti.service; 2 | 3 | import com.wj.activiti.entity.Permission; 4 | import com.wj.activiti.entity.User; 5 | import com.wj.activiti.reposity.UserMapper; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.security.core.GrantedAuthority; 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 11 | import org.springframework.stereotype.Service; 12 | 13 | import javax.annotation.Resource; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | @Slf4j 18 | @Service 19 | public class UserServiceImpl implements UserService { 20 | 21 | @Resource 22 | private UserMapper userMapper; 23 | 24 | @Override 25 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 26 | // 1.根据用户名称查询到user用户
 27 | User userDetails = userMapper.findByUsername(username); 28 | if (userDetails == null) { 29 | return null; 30 | } 31 | // 2.查询该用户对应的权限
 32 | List permissionList = userMapper.findPermissionByUsername(username); 33 | List grantedAuthorities = new ArrayList<>(); 34 | permissionList.forEach((a) -> grantedAuthorities.add(new SimpleGrantedAuthority(a.getName()))); 35 | log.info(">>permissionList:{}<<", permissionList); 36 | // 设置权限
 37 | userDetails.setAuthorities(grantedAuthorities); 38 | return userDetails; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:mysql://localhost:3306/activiti_spring?useUnicode=true&characterEncoding=utf8&nullCatalogMeansCurrent=true 4 | username: root 5 | password: 123456 6 | driver-class-name: com.mysql.cj.jdbc.Driver 7 | activiti: 8 | # flase: 默认值。activiti在启动时,会对比数据库表中保存的版本,如果没有表或者版本不匹配,将抛出异常。(生产环境常用) 9 | # true: activiti会对数据库中所有表进行更新操作。如果表不存在,则自动创建。(开发时常用) 10 | # create_drop: 在activiti启动时创建表,在关闭时删除表(必须手动关闭引擎,才能删除表)。(单元测试常用) 11 | # drop-create: 在activiti启动时删除原来的旧表,然后在创建新表(不需要手动关闭引擎)。 12 | database-schema-update: true 13 | #默认不生成历史表,这里开启 14 | db-history-used: true 15 | #历史登记 16 | # none: 不记录历史流程,性能高,流程结束后不可读取 17 | # activity: 归档流程实例和活动实例,流程变量不同步 18 | # audit: 默认值,在activiti基础上同步变量值,保存表单属性 19 | # full: 性能较差,记录所有实例和变量细节变化,最完整的历史记录,如果需要日后跟踪详细可以开启full(一般不建议开启) 20 | history-level: full 21 | deployment-mode: never-fail # 关闭 SpringAutoDeployment 22 | #校验流程文件,默认校验resources 目录下的 process里的流程 文件 23 | # check-process-definitions: false 24 | # project manifest path 25 | #project: 26 | # manifest: 27 | # file: 28 | # path: classpath:/default-project.json -------------------------------------------------------------------------------- /activiti/activiti/src/main/resources/default-project.json: -------------------------------------------------------------------------------- 1 | { 2 | "createdBy": "superadminuser", 3 | "creationDate": "2019-08-16T15:58:46.056+0000", 4 | "lastModifiedBy": "qa-modeler-1", 5 | "lastModifiedDate": "2019-08-16T16:03:41.941+0000", 6 | "id": "c519a458-539f-4385-a937-2edfb4045eb9", 7 | "name": "projectA", 8 | "description": "", 9 | "version": "1" 10 | } -------------------------------------------------------------------------------- /activiti/activiti/src/main/resources/processes/leaveApplication.bpmn20.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /activiti/activiti/src/main/resources/processes/myEvection.bpmn20.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /activiti/activiti_demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.example 8 | activiti_demo 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | org.activiti 14 | activiti-engine 15 | 7.1.0.M6 16 | 17 | 18 | org.activiti 19 | activiti-spring 20 | 7.1.0.M6 21 | 22 | 23 | org.activiti 24 | activiti-bpmn-model 25 | 7.1.0.M6 26 | 27 | 28 | 29 | org.activiti 30 | activiti-bpmn-converter 31 | 7.1.0.M6 32 | 33 | 34 | 35 | org.activiti 36 | activiti-json-converter 37 | 7.1.0.M6 38 | 39 | 40 | 41 | org.activiti 42 | activiti-bpmn-layout 43 | 7.1.0.M6 44 | 45 | 46 | 47 | org.activiti.cloud 48 | activiti-cloud-services-api 49 | 7.0.0.Beta1 50 | 51 | 52 | 53 | mysql 54 | mysql-connector-java 55 | 8.0.29 56 | 57 | 58 | 59 | commons-dbcp 60 | commons-dbcp 61 | 1.4 62 | 63 | 64 | 65 | 66 | org.projectlombok 67 | lombok 68 | 1.18.24 69 | true 70 | 71 | 72 | 73 | org.apache.logging.log4j 74 | log4j-slf4j-impl 75 | 2.17.2 76 | 77 | 78 | junit 79 | junit 80 | 4.12 81 | test 82 | 83 | 84 | 85 | commons-io 86 | commons-io 87 | 2.11.0 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /activiti/activiti_demo/src/main/resources/activiti.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /activiti/activiti_demo/src/main/resources/bpmn/leaveApplication.bpmn20.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /activiti/activiti_demo/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /activiti/activiti_demo/src/test/java/com/wj/activiti/TestCreat.java: -------------------------------------------------------------------------------- 1 | package com.wj.activiti; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.activiti.engine.*; 5 | import org.activiti.engine.history.HistoricActivityInstance; 6 | import org.activiti.engine.history.HistoricActivityInstanceQuery; 7 | import org.activiti.engine.repository.Deployment; 8 | import org.activiti.engine.repository.ProcessDefinition; 9 | import org.activiti.engine.runtime.ProcessInstance; 10 | import org.activiti.engine.task.Task; 11 | import org.apache.commons.io.IOUtils; 12 | import org.junit.Test; 13 | 14 | import java.io.File; 15 | import java.io.FileOutputStream; 16 | import java.io.IOException; 17 | import java.io.InputStream; 18 | import java.util.List; 19 | @Slf4j 20 | public class TestCreat { 21 | /** 22 | * 数据库表结构的创建 23 | */ 24 | @Test 25 | public void testCreateDbTable(){ 26 | /** 27 | * 创建 processEngine 时,会自动加载 /resources 目录下的 activiti.cfg.xml 文件 28 | * 进行 mysql 数据库中表的创建 29 | */ 30 | ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); 31 | 32 | log.info(processEngine.getName()); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /demo/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /demo/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/demo/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /demo/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.2.5.RELEASE 9 | 10 | 11 | com.shumile 12 | demo 13 | 0.0.1-SNAPSHOT 14 | demo 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.projectlombok 29 | lombok 30 | true 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-test 35 | test 36 | 37 | 38 | org.junit.vintage 39 | junit-vintage-engine 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-maven-plugin 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /demo/src/main/java/com/shumile/demo/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.shumile.demo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DemoApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(DemoApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /demo/src/main/java/com/shumile/demo/HelloController.java: -------------------------------------------------------------------------------- 1 | package com.shumile.demo; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | @RequestMapping("/") 9 | public class HelloController { 10 | @GetMapping("/hello") 11 | public String helloWorld(){ 12 | return "hello,world~"; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.servlet.context-path=/shumile 2 | -------------------------------------------------------------------------------- /demo/src/test/java/com/shumile/demo/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.shumile.demo; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class DemoApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /druid_demo/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /druid_demo/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /druid_demo/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /druid_demo/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /druid_demo/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/druid_demo/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /druid_demo/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /druid_demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.2.5.RELEASE 9 | 10 | 11 | com.shumile 12 | druid_demo 13 | 0.0.1-SNAPSHOT 14 | druid_demo 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-jdbc 26 | 27 | 28 | 29 | HikariCP 30 | com.zaxxer 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | com.alibaba 39 | druid-spring-boot-starter 40 | 1.1.10 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter 45 | 46 | 47 | 48 | mysql 49 | mysql-connector-java 50 | runtime 51 | 52 | 53 | org.projectlombok 54 | lombok 55 | true 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-starter-test 60 | test 61 | 62 | 63 | org.junit.vintage 64 | junit-vintage-engine 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-maven-plugin 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /druid_demo/src/main/java/com/shumile/druid_demo/DruidDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.shumile.druid_demo; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.ApplicationArguments; 5 | import org.springframework.boot.ApplicationRunner; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | 9 | @SpringBootApplication 10 | public class DruidDemoApplication implements ApplicationRunner { 11 | @Autowired 12 | private UserDao userDao; 13 | 14 | public static void main(String[] args) { 15 | SpringApplication.run(DruidDemoApplication.class, args); 16 | } 17 | 18 | 19 | @Override 20 | public void run(ApplicationArguments args) throws Exception { 21 | userDao.addUser(); 22 | userDao.listData(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /druid_demo/src/main/java/com/shumile/druid_demo/User.java: -------------------------------------------------------------------------------- 1 | package com.shumile.druid_demo; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Data 7 | @Builder 8 | public class User { 9 | private long id; 10 | 11 | private String name; 12 | 13 | private int age; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /druid_demo/src/main/java/com/shumile/druid_demo/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.shumile.druid_demo; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.jdbc.core.JdbcTemplate; 6 | import org.springframework.jdbc.core.RowMapper; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import java.sql.ResultSet; 10 | import java.sql.SQLException; 11 | import java.util.List; 12 | 13 | @Slf4j 14 | @Repository 15 | public class UserDao { 16 | @Autowired 17 | private JdbcTemplate jdbcTemplate; 18 | /** 19 | * 添加用户 20 | */ 21 | public void addUser() { 22 | User user = User.builder().name("舒米君").age(18).build(); 23 | jdbcTemplate.update 24 | ("insert t_user values(?,?,?)", 25 | new Object[]{user.getId(), user.getName(), user.getAge()} 26 | ); 27 | log.info("user :{} added",user); 28 | } 29 | /** 30 | * 获取总数 31 | * 32 | * @return 33 | */ 34 | private Long getCount() { 35 | 36 | return jdbcTemplate 37 | .queryForObject("select count(1) from t_user", Long.class); 38 | } 39 | 40 | /** 41 | * 采用RowMapper的方式,获取结果对象。 42 | */ 43 | public void listData() { 44 | log.info("Count:{}", getCount()); 45 | //采用RowMapper的方式,获取结果对象。 46 | List userList2 = jdbcTemplate.query("select * from t_user", new RowMapper() { 47 | @Override 48 | public User mapRow(ResultSet resultSet, int i) throws SQLException { 49 | return User.builder() 50 | .id(resultSet.getLong(1) 51 | ).name(resultSet.getString("name") 52 | ).age(resultSet.getInt("age")) 53 | .build(); 54 | } 55 | }); 56 | userList2.forEach(user -> log.info("User2:{}", user)); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /druid_demo/src/main/java/com/shumile/druid_demo/filter/ConnectionLogFilter.java: -------------------------------------------------------------------------------- 1 | package com.shumile.druid_demo.filter; 2 | 3 | import com.alibaba.druid.filter.FilterChain; 4 | import com.alibaba.druid.filter.FilterEventAdapter; 5 | import com.alibaba.druid.proxy.jdbc.ConnectionProxy; 6 | import lombok.extern.slf4j.Slf4j; 7 | 8 | import java.util.Properties; 9 | 10 | @Slf4j 11 | public class ConnectionLogFilter extends FilterEventAdapter { 12 | 13 | @Override 14 | public void connection_connectBefore(FilterChain chain, 15 | Properties info) { 16 | log.info("BEFORE CONNECTION!"); 17 | } 18 | 19 | @Override 20 | public void connection_connectAfter(ConnectionProxy connection) { 21 | log.info("AFTER CONNECTION!"); 22 | } 23 | } -------------------------------------------------------------------------------- /druid_demo/src/main/resources/META-INF/druid-filter.properties: -------------------------------------------------------------------------------- 1 | druid.filters.conn=com.shumile.druid_demo.filter.ConnectionLogFilter 2 | -------------------------------------------------------------------------------- /druid_demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8 2 | spring.datasource.username=root 3 | spring.datasource.password=123456 4 | 5 | #可以不用配置数据库驱动,SpringBoot 会根据引入的依赖进行自动配置 6 | #spring.datasource.driver-class-name=com.mysql.jdbc.Driver 7 | 8 | 9 | spring.datasource.druid.initial-size=5 10 | spring.datasource.druid.max-active=5 11 | spring.datasource.druid.min-idle=5 12 | 13 | spring.datasource.druid.filter.config.enabled=true 14 | #其中conn为自己扩展的 15 | spring.datasource.druid.filters=conn,config,stat,slf4j 16 | 17 | #spring.datasource.druid.connection-properties=config.decrypt=true;config.decrypt.key=${public-key} 18 | 19 | spring.datasource.druid.test-on-borrow=true 20 | spring.datasource.druid.test-on-return=true 21 | spring.datasource.druid.test-while-idle=true 22 | 23 | #慢sql打印配置 24 | spring.datasource.druid.filter.stat.log-slow-sql=true 25 | spring.datasource.druid.filter.stat.slow-sql-millis=1 26 | #public-key=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALS8ng1XvgHrdOgm4pxrnUdt3sXtu/E8My9KzX8sXlz+mXRZQCop7NVQLne25pXHtZoDYuMh3bzoGj6v5HvvAQ8CAwEAAQ== 27 | 28 | #sql防注入配置 29 | spring.datasource.druid.filter.wall.enabled=true 30 | spring.datasource.druid.filter.wall.db-type=mysql 31 | spring.datasource.druid.filter.wall.config.delete-allow=false 32 | spring.datasource.druid.filter.wall.config.drop-table-allow=false 33 | -------------------------------------------------------------------------------- /druid_demo/src/test/java/com/shumile/druid_demo/DruidDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.shumile.druid_demo; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class DruidDemoApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /hystrix_demo/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /hystrix_demo/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/hystrix_demo/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /hystrix_demo/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /hystrix_demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.2.5.RELEASE 9 | 10 | 11 | com.shumile 12 | hystrix_demo 13 | 0.0.1-SNAPSHOT 14 | hystrix_demo 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.projectlombok 29 | lombok 30 | true 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-test 35 | test 36 | 37 | 38 | org.junit.vintage 39 | junit-vintage-engine 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-maven-plugin 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /hystrix_demo/src/main/java/com/shumile/hystrix_demo/HystrixDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.shumile.hystrix_demo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class HystrixDemoApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(HystrixDemoApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /hystrix_demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /hystrix_demo/src/test/java/com/shumile/hystrix_demo/HystrixDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.shumile.hystrix_demo; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class HystrixDemoApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jwt_demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.springframework.boot 8 | spring-boot-starter-parent 9 | 2.7.0 10 | 11 | 12 | org.example 13 | jwt_demo 14 | 1.0-SNAPSHOT 15 | 16 | 17 | 18 | org.springframework.boot 19 | spring-boot-starter 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.projectlombok 29 | lombok 30 | true 31 | 32 | 33 | com.auth0 34 | java-jwt 35 | 3.7.0 36 | 37 | 38 | 39 | cn.hutool 40 | hutool-all 41 | 5.8.4.M1 42 | 43 | 44 | 45 | mysql 46 | mysql-connector-java 47 | 48 | 49 | com.alibaba 50 | druid-spring-boot-starter 51 | 1.2.9 52 | 53 | 54 | tk.mybatis 55 | mapper-spring-boot-starter 56 | 2.1.5 57 | 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-starter-data-redis 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/JwtApplication.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | @MapperScan("com.wj.jwt.reposity") 9 | public class JwtApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(JwtApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/annotation/IgnoreToken.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target({ElementType.METHOD, ElementType.TYPE}) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface IgnoreToken { 11 | boolean required() default true; 12 | } -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/config/WebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.config; 2 | 3 | import com.wj.jwt.handler.AuthorisationInterceptor; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 8 | 9 | @Configuration 10 | public class WebMvcConfig implements WebMvcConfigurer { 11 | 12 | @Bean 13 | public AuthorisationInterceptor authorazationIntercepter(){ 14 | return new AuthorisationInterceptor(); 15 | } 16 | @Override 17 | public void addInterceptors(InterceptorRegistry registry) { 18 | // 添加拦截器 19 | registry.addInterceptor(authorazationIntercepter()) 20 | //指定需要拦截的路径 21 | .addPathPatterns("/user/**"); 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.controller; 2 | 3 | 4 | import cn.hutool.core.util.StrUtil; 5 | import com.wj.jwt.entity.User; 6 | import com.wj.jwt.service.JwtService; 7 | import com.wj.jwt.service.UserService; 8 | import com.wj.jwt.util.MD5Util; 9 | import com.wj.jwt.vo.ResponseResult; 10 | import com.wj.jwt.vo.UserVo; 11 | import org.springframework.data.redis.core.RedisTemplate; 12 | import org.springframework.web.bind.annotation.PostMapping; 13 | import org.springframework.web.bind.annotation.RequestParam; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | import javax.annotation.Resource; 17 | import java.util.UUID; 18 | import java.util.concurrent.TimeUnit; 19 | 20 | @RestController 21 | public class LoginController { 22 | 23 | @Resource 24 | private JwtService jwtService; 25 | 26 | @Resource 27 | private UserService userService; 28 | 29 | @Resource 30 | private RedisTemplate redisTemplate; 31 | 32 | 33 | @PostMapping("/session/login") 34 | public String sessionLogin(String username,String password) throws Exception { 35 | //1-校验用户名密码是否为空 36 | if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){ 37 | throw new Exception("用户名或密码不能为空!"); 38 | } 39 | 40 | // 2-根据用户查询用户是否存在 41 | User user = userService.findByUsername(username); 42 | if (user == null){ 43 | throw new Exception("用户名或密码有误!"); 44 | } 45 | 46 | //2-对密码进行加密加盐处理 47 | password = MD5Util.md5slat(password); 48 | if (!password.equalsIgnoreCase(user.getPassword())){ 49 | throw new Exception("用户名或密码有误!"); 50 | } 51 | return "success!"; 52 | } 53 | 54 | 55 | @PostMapping("/jwt/login") 56 | public ResponseResult login(String username,String password) throws Exception { 57 | //1-校验用户名密码是否为空 58 | if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){ 59 | throw new Exception("用户名或密码不能为空!"); 60 | } 61 | 62 | // 2-根据用户查询用户是否存在 63 | User user = userService.findByUsername(username); 64 | if (user == null){ 65 | throw new Exception("用户名或密码有误!"); 66 | } 67 | //3-验证用户名密码 68 | password = MD5Util.md5slat(password); 69 | if (!password.equalsIgnoreCase(user.getPassword())){ 70 | throw new Exception("用户名或密码有误!"); 71 | } 72 | UserVo userVo = UserVo.builder().build(); 73 | userVo.setId(user.getId()); 74 | userVo.setUsername(username); 75 | userVo.setPassword(password); 76 | String token = jwtService.token(userVo); 77 | userVo.setToken(token); 78 | userVo.setRefreshToken(UUID.randomUUID().toString()); 79 | //同时存储用户到 redis 中 80 | redisTemplate.opsForValue().set(token,userVo,JwtService.TOKEN_EXSPIRE_TIME, TimeUnit.SECONDS); 81 | return new ResponseResult(userVo); 82 | } 83 | 84 | @PostMapping("refreshToken") 85 | public ResponseResult refreshToken(@RequestParam("token") String oldToken){ 86 | //1-获取 token 87 | UserVo userVo = redisTemplate.opsForValue().get(oldToken); 88 | if (userVo == null){ 89 | return new ResponseResult(500,"user not found!",null); 90 | } 91 | 92 | String token = jwtService.token(userVo); 93 | userVo.setToken(token); 94 | userVo.setRefreshToken(UUID.randomUUID().toString()); 95 | //同时存储用户到 redis 中 96 | redisTemplate.delete(oldToken); 97 | redisTemplate.opsForValue().set(token,userVo,JwtService.TOKEN_EXSPIRE_TIME +10000, TimeUnit.SECONDS); 98 | return new ResponseResult(userVo); 99 | 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.controller; 2 | 3 | import com.wj.jwt.annotation.IgnoreToken; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RequestParam; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | @RequestMapping("/user") 11 | public class UserController { 12 | 13 | @IgnoreToken 14 | @GetMapping("/common") 15 | public String common() { 16 | return "hello~ common"; 17 | } 18 | 19 | @GetMapping("/admin") 20 | public String admin() { 21 | return "hello~ admin"; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.entity; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Data 7 | @Builder 8 | public class User { 9 | 10 | private Long id; 11 | 12 | private String username; 13 | 14 | private String password; 15 | 16 | private String token; 17 | 18 | private String refreshToken; 19 | } 20 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/handler/AuthorisationInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.handler; 2 | 3 | import cn.hutool.core.util.StrUtil; 4 | import com.wj.jwt.annotation.IgnoreToken; 5 | import com.wj.jwt.service.JwtService; 6 | import com.wj.jwt.vo.ResponseResult; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.web.method.HandlerMethod; 11 | import org.springframework.web.servlet.HandlerInterceptor; 12 | import org.springframework.web.servlet.ModelAndView; 13 | 14 | import javax.servlet.http.HttpServletRequest; 15 | import javax.servlet.http.HttpServletResponse; 16 | import javax.xml.bind.ValidationException; 17 | import java.lang.reflect.Method; 18 | 19 | @Slf4j 20 | public class AuthorisationInterceptor implements HandlerInterceptor { 21 | 22 | @Autowired 23 | private JwtService jwtService; 24 | 25 | @Value("${spring.profiles.active}") 26 | private String profiles; 27 | 28 | private static final String AUTH = "Authorization"; 29 | private static final String AUTH_USERNAME = "username"; 30 | 31 | @Override 32 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 33 | log.info("执行了 AuthorisationInterceptor 的 preHandle 方法"); 34 | 35 | //1-过滤开发环境,开发环境不需要验证token 36 | if (!StrUtil.isBlank(profiles) && "dev".equals(profiles) ){ 37 | return true; 38 | } 39 | //2-ignoreToken,不需要验证 token 40 | if (ignoreToken((HandlerMethod) handler)) return true; 41 | 42 | //3- 获取 token 43 | String token = getParamValue(request, AUTH); 44 | 45 | //4- 获取并验证 username 46 | String username = getParamValue(request, AUTH_USERNAME); 47 | ResponseResult responseResult = jwtService.verifyUsername(token, username); 48 | if (responseResult.getStatus()!=1){ 49 | log.error("用户名校验失败"); 50 | throw new ValidationException("300","用户名校验失败!"); 51 | } 52 | //这里需要注意: 53 | // 1)如果设置为false时,被请求时,拦截器执行到此处将不会继续操作 54 | // 2)如果设置为true时,请求将会继续执行后面的操作 55 | return true; 56 | 57 | 58 | } 59 | 60 | @Override 61 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 62 | log.info("执行了 AuthorisationInterceptor 的 postHandle 方法"); 63 | 64 | 65 | } 66 | 67 | @Override 68 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 69 | log.info("执行了 AuthorisationInterceptor 的 afterCompletion 方法"); 70 | } 71 | 72 | 73 | private String getParamValue(HttpServletRequest request, String filed) throws ValidationException { 74 | String value = getParam(request,filed); 75 | 76 | if (StrUtil.isEmpty(value)){ 77 | throw new ValidationException("300",filed+"不允许为空,请重新登录!"); 78 | } 79 | 80 | return value; 81 | } 82 | 83 | /** 84 | * 获取参数的值 -- 若参数中不存在,则从请求头中获取 85 | * @param request 请求 86 | * @param filedName 参数名称 87 | * @return 88 | */ 89 | private static String getParam(HttpServletRequest request,String filedName){ 90 | String param = request.getParameter(filedName); 91 | if (StrUtil.isEmpty(param)){ 92 | param = request.getHeader(filedName); 93 | } 94 | return param; 95 | } 96 | 97 | /** 98 | * 忽略 token 的处理 99 | * @param handler 100 | * @return 101 | */ 102 | private boolean ignoreToken(HandlerMethod handler) { 103 | Method method = handler.getMethod(); 104 | if (method.isAnnotationPresent(IgnoreToken.class)){ 105 | IgnoreToken ignoreToken = method.getAnnotation(IgnoreToken.class); 106 | return ignoreToken.required(); 107 | } 108 | return false; 109 | } 110 | } 111 | 112 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/reposity/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.reposity; 2 | 3 | 4 | import com.wj.jwt.entity.User; 5 | import org.apache.ibatis.annotations.Param; 6 | import org.apache.ibatis.annotations.Select; 7 | 8 | public interface UserMapper { 9 | 10 | /** 11 | * 根据用户名称查询 12 | * 13 | * @param userName 14 | * @return 15 | */ 16 | @Select(" select * from user where username = #{userName}") 17 | User findByUsername(@Param("userName") String userName); 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/service/JwtService.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.service; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.auth0.jwt.JWTVerifier; 5 | import com.auth0.jwt.algorithms.Algorithm; 6 | import com.wj.jwt.vo.ResponseResult; 7 | import com.wj.jwt.vo.UserVo; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.Date; 12 | 13 | @Slf4j 14 | @Service 15 | public class JwtService { 16 | //加密秘钥 17 | private static final String SECRET_KEY = "wangjienihao"; 18 | // 签发人 19 | private static final String ISSUER = "jiege"; 20 | // token 过期时间 21 | public static final Long TOKEN_EXSPIRE_TIME = 1000 * 60 * 60 * 10L; 22 | 23 | /** 24 | * 生成 token 25 | * @param userVo 用户信息 26 | * @return 27 | */ 28 | public String token(UserVo userVo) { 29 | //1-确定加密算法 30 | Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); 31 | Date now = new Date(); 32 | //2-开始创建和生成 token 33 | return JWT.create() 34 | .withIssuedAt(now) 35 | .withIssuer(ISSUER) 36 | .withExpiresAt(new Date(now.getTime() + TOKEN_EXSPIRE_TIME))//token 的过期时间 37 | .withClaim("username", userVo.getUsername()) 38 | .withClaim("password", userVo.getPassword()) 39 | .sign(algorithm); 40 | } 41 | 42 | /** 43 | * 校验用户名 44 | * @param token token 45 | * @param username 用户名 46 | * @return 47 | */ 48 | public ResponseResult verifyUsername(String token,String username){ 49 | log.info("verify jwt-username - {}",username); 50 | ResponseResult responseResult = new ResponseResult(); 51 | try { 52 | //1-定义算法 53 | Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); 54 | //2-进行校验 55 | JWTVerifier jwtVerifier = JWT.require(algorithm) 56 | .withIssuer(ISSUER) 57 | .withClaim("username", username) 58 | .build(); 59 | jwtVerifier.verify(token); 60 | } catch (Exception ex){ 61 | responseResult.setStatus(-1); 62 | responseResult.setMessage("失败!"); 63 | log.error("auth verify fail:{}",ex.getMessage()); 64 | } 65 | return responseResult; 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.service; 2 | 3 | 4 | import com.wj.jwt.entity.User; 5 | 6 | public interface UserService { 7 | 8 | User findByUsername(String username); 9 | } -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.service; 2 | 3 | import com.wj.jwt.entity.User; 4 | import com.wj.jwt.reposity.UserMapper; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.stereotype.Service; 7 | 8 | import javax.annotation.Resource; 9 | 10 | @Slf4j 11 | @Service 12 | public class UserServiceImpl implements UserService { 13 | 14 | @Resource 15 | private UserMapper userMapper; 16 | 17 | 18 | @Override 19 | public User findByUsername(String username) { 20 | return userMapper.findByUsername(username); 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/util/MD5Util.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.util; 2 | 3 | import java.math.BigInteger; 4 | import java.nio.charset.StandardCharsets; 5 | import java.security.MessageDigest; 6 | 7 | /** 8 | * MD5Util 工具类 9 | */ 10 | public class MD5Util { 11 | public static String md5(String str) { 12 | try { 13 | MessageDigest md5 = MessageDigest.getInstance("MD5"); 14 | md5.update(str.getBytes(StandardCharsets.UTF_8)); 15 | return bytesToHex(md5.digest()); 16 | } catch (Exception var2) { 17 | throw new RuntimeException(var2); 18 | } 19 | } 20 | 21 | public static String md5slat(String str){ 22 | return MD5Util.md5(MD5Util.md5("jiege"+str+"123")); 23 | } 24 | 25 | public static String bytesToHex(byte[] bytes) { 26 | BigInteger bigInt = new BigInteger(1, bytes); 27 | 28 | String hashtext; 29 | for(hashtext = bigInt.toString(16); hashtext.length() < 32; hashtext = "0" + hashtext) { 30 | } 31 | 32 | return hashtext; 33 | } 34 | 35 | public static void main(String[] args) { 36 | System.out.println(md5slat("123456")); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/vo/ResponseResult.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.vo; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | 6 | @Data 7 | @NoArgsConstructor 8 | public class ResponseResult { 9 | 10 | private Integer status = 1; // 1 成功 -1,失败 11 | 12 | private String message = "成功!"; 13 | 14 | private Object data; 15 | 16 | 17 | public ResponseResult(Integer status, String message){ 18 | this.status = status; 19 | this.message = message; 20 | } 21 | 22 | public ResponseResult(Object data){ 23 | this.data = data; 24 | } 25 | 26 | public ResponseResult(Integer status, String message,Object data){ 27 | this(status,message); 28 | this.data = data; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /jwt_demo/src/main/java/com/wj/jwt/vo/UserVo.java: -------------------------------------------------------------------------------- 1 | package com.wj.jwt.vo; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | import java.io.Serializable; 7 | 8 | @Data 9 | @Builder 10 | public class UserVo implements Serializable { 11 | 12 | private Long id; 13 | 14 | private String username; 15 | 16 | private String password; 17 | 18 | private String token; 19 | 20 | private String refreshToken; 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /jwt_demo/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8086 3 | 4 | spring: 5 | datasource: 6 | url: jdbc:mysql://localhost:3306/jwt_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false 7 | username: root 8 | password: 123456 9 | profiles: 10 | #默认配置为dev,会在开发调试时跳过token 的校验,提高调试效率 11 | active: prod 12 | 13 | -------------------------------------------------------------------------------- /mybatis_demo2/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /mybatis_demo2/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/mybatis_demo2/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /mybatis_demo2/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /mybatis_demo2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.2.5.RELEASE 9 | 10 | 11 | com.shumile 12 | mybatis_demo2 13 | 0.0.1-SNAPSHOT 14 | mybatis_demo2 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.mybatis.spring.boot 24 | mybatis-spring-boot-starter 25 | 2.1.2 26 | 27 | 28 | 29 | mysql 30 | mysql-connector-java 31 | runtime 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-test 36 | test 37 | 38 | 39 | org.junit.vintage 40 | junit-vintage-engine 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-maven-plugin 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /mybatis_demo2/src/main/java/com/shumile/mybatis_demo2/MybatisDemo2Application.java: -------------------------------------------------------------------------------- 1 | package com.shumile.mybatis_demo2; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class MybatisDemo2Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(MybatisDemo2Application.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /mybatis_demo2/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /mybatis_demo2/src/test/java/com/shumile/mybatis_demo2/MybatisDemo2ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.shumile.mybatis_demo2; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class MybatisDemo2ApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /spring-boot-jpa/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /spring-boot-jpa/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/spring-boot-jpa/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-jpa/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /spring-boot-jpa/out/production/.mvn/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/spring-boot-jpa/out/production/.mvn/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-jpa/out/production/.mvn/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /spring-boot-jpa/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.2.5.RELEASE 9 | 10 | 11 | com.shumile 12 | spring-boot-jpa 13 | 0.0.1-SNAPSHOT 14 | spring-boot-jpa 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-data-jpa 25 | 26 | 27 | 28 | mysql 29 | mysql-connector-java 30 | runtime 31 | 32 | 33 | org.projectlombok 34 | lombok 35 | true 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-test 40 | test 41 | 42 | 43 | org.junit.vintage 44 | junit-vintage-engine 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-maven-plugin 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /spring-boot-jpa/src/main/java/com/shumile/springbootjpa/SpringBootJpaApplication.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootjpa; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.ApplicationArguments; 6 | import org.springframework.boot.ApplicationRunner; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 10 | 11 | import java.util.Date; 12 | import java.util.List; 13 | 14 | @SpringBootApplication 15 | @Slf4j 16 | @EnableJpaRepositories 17 | public class SpringBootJpaApplication implements ApplicationRunner { 18 | 19 | @Autowired 20 | private UserRepository userRepository; 21 | 22 | 23 | @Override 24 | public void run(ApplicationArguments args) throws Exception { 25 | User user = User.builder() 26 | .name("小米") 27 | .createTime(new Date()) 28 | .updateTime(new Date()) 29 | .build(); 30 | userRepository.save(user); 31 | log.info("one user added :{}",user); 32 | 33 | Iterable users = userRepository.findAll(); 34 | users.forEach(System.out::println); 35 | 36 | //调用自定义查询方法 37 | // List userList = userRepository.findByNameOrderByCreateTimeDesc("小米"); 38 | // log.info("userList:{}",userList); 39 | 40 | } 41 | 42 | public static void main(String[] args) { 43 | SpringApplication.run(SpringBootJpaApplication.class, args); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /spring-boot-jpa/src/main/java/com/shumile/springbootjpa/Test.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootjpa; 2 | 3 | import java.util.*; 4 | 5 | public class Test { 6 | public static void main(String[] args) { 7 | String mapList = "0:message_type,2:card_no,3:processing_code"; 8 | if (mapList==null ||mapList.equals("")){ 9 | //logger.error("配置文件中后端域的映射,配置有误:{}",,mapList); 10 | throw new RuntimeException("配置文件中后端域的映射,配置有误,请检查配置"); 11 | 12 | } 13 | List list = Arrays.asList(mapList.split(","));//根据逗号分隔转化为list 14 | List> maps = new ArrayList<>(); 15 | Map map = new HashMap<>(); 16 | for (String keyValue : list) { 17 | String[] mapsStr = keyValue.split(":"); 18 | if (mapsStr!=null && mapsStr.length==2){ 19 | map.put(mapsStr[0], mapsStr[1]); 20 | maps.add(map); 21 | } 22 | } 23 | System.out.println(maps); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /spring-boot-jpa/src/main/java/com/shumile/springbootjpa/User.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootjpa; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | import org.hibernate.annotations.CreationTimestamp; 8 | import org.hibernate.annotations.UpdateTimestamp; 9 | 10 | import javax.persistence.*; 11 | import java.io.Serializable; 12 | import java.util.Date; 13 | 14 | @Entity 15 | @Table(name = "USER") 16 | @Builder 17 | @Data 18 | @NoArgsConstructor 19 | @AllArgsConstructor 20 | public class User implements Serializable { 21 | @Id 22 | @GeneratedValue 23 | private Long id; 24 | private String name; 25 | @Column(updatable = false) 26 | @CreationTimestamp 27 | private Date createTime; 28 | @UpdateTimestamp 29 | private Date updateTime; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /spring-boot-jpa/src/main/java/com/shumile/springbootjpa/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootjpa; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | import java.util.List; 6 | 7 | public interface UserRepository extends CrudRepository { 8 | 9 | List findByNameOrderByCreateTimeDesc(String name); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /spring-boot-jpa/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #1、数据库连接信息配置 2 | spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8 3 | spring.datasource.username=root 4 | spring.datasource.password=123456 5 | #可以不用配置数据库驱动,SpringBoot 会根据引入的依赖进行自动配置 6 | #spring.datasource.driver-class-name=com.mysql.jdbc.Driver 7 | 8 | #2、jpa配置信息 9 | 10 | #建表机制 11 | #create-drop - 运行程序新建,程序结束:删表 12 | #create -运行程序会新建表,程序结束:表的数据会清空 13 | #update - 没有表格时会新建表格,表内有数据不会清空,只会更新, 14 | #valid - 运行程序会校验数据与数据库的字段类型是否相同,不同会报错 15 | spring.jpa.hibernate.ddl-auto=update 16 | #打印sql开关 17 | spring.jpa.properties.hibernate.show_sql=true 18 | #是否格式化sql 19 | spring.jpa.properties.hibernate.format_sql=true 20 | -------------------------------------------------------------------------------- /spring-boot-jpa/src/test/java/com/shumile/springbootjpa/SpringBootJpaApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootjpa; 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /spring-boot-mybatis/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /spring-boot-mybatis/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/spring-boot-mybatis/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-mybatis/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /spring-boot-mybatis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.2.5.RELEASE 9 | 10 | 11 | com.shumile 12 | spring-boot-mybatis 13 | 0.0.1-SNAPSHOT 14 | spring-boot-mybatis 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.mybatis.spring.boot 24 | mybatis-spring-boot-starter 25 | 2.1.2 26 | 27 | 28 | 29 | mysql 30 | mysql-connector-java 31 | runtime 32 | 33 | 34 | org.projectlombok 35 | lombok 36 | true 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-test 43 | test 44 | 45 | 46 | 47 | 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-maven-plugin 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /spring-boot-mybatis/src/main/java/com/shumile/springbootmybatis/SpringBootMybatisApplication.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootmybatis; 2 | 3 | import com.shumile.springbootmybatis.mapper.UserMapperWithAnnotation; 4 | import com.shumile.springbootmybatis.mapper.UserMapperWithBuilder; 5 | import com.shumile.springbootmybatis.mapper.UserMapperWithXml; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.mybatis.spring.annotation.MapperScan; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.ApplicationArguments; 10 | import org.springframework.boot.ApplicationRunner; 11 | import org.springframework.boot.SpringApplication; 12 | import org.springframework.boot.autoconfigure.SpringBootApplication; 13 | import org.springframework.transaction.annotation.EnableTransactionManagement; 14 | import org.springframework.transaction.annotation.Transactional; 15 | import java.util.Date; 16 | import java.util.HashMap; 17 | import java.util.List; 18 | import java.util.Map; 19 | 20 | @SpringBootApplication 21 | @Slf4j 22 | @MapperScan("com.shumile.springbootmybatis.mapper") 23 | @EnableTransactionManagement 24 | public class SpringBootMybatisApplication implements ApplicationRunner { 25 | 26 | @Autowired 27 | private UserMapperWithAnnotation userMapperWithAnnotation; 28 | @Autowired 29 | private UserMapperWithXml userMapperWithXml; 30 | 31 | @Autowired 32 | private UserMapperWithBuilder userMapperWithBuilder; 33 | 34 | public static void main(String[] args) { 35 | SpringApplication.run(SpringBootMybatisApplication.class, args); 36 | } 37 | 38 | @Override 39 | @Transactional 40 | public void run(ApplicationArguments args) throws Exception { 41 | //testByMapper(); 42 | testCache(); 43 | //testByXml(); 44 | //testBuilder(); 45 | 46 | } 47 | private void testBuilder(){ 48 | userMapperWithBuilder.selectUserById(18l); 49 | } 50 | //@Transactional 51 | public void testCache(){ 52 | User user = userMapperWithAnnotation.findById(32L); 53 | log.info("Find User: {}", user); 54 | 55 | User user2 = userMapperWithAnnotation.findById(32L); 56 | log.info("Find User2: {}", user2); 57 | } 58 | 59 | private void testByXml() { 60 | Map map = new HashMap<>(); 61 | map.put("name","小米"); 62 | map.put("age",17); 63 | List userList = userMapperWithXml.getUserList(map); 64 | userList.forEach(user->log.info("user:{}",user)); 65 | } 66 | 67 | private void testByMapper() { 68 | User c = User.builder().name("小米").age(17) 69 | .createTime(new Date()) 70 | .updateTime(new Date()).build(); 71 | int count = userMapperWithAnnotation.save(c); 72 | log.info("Save {} User: {}", count, c); 73 | 74 | c = userMapperWithAnnotation.findById(c.getId()); 75 | log.info("Find User: {}", c); 76 | 77 | } 78 | 79 | 80 | } 81 | -------------------------------------------------------------------------------- /spring-boot-mybatis/src/main/java/com/shumile/springbootmybatis/User.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootmybatis; 2 | import java.io.Serializable; 3 | import java.util.Date; 4 | 5 | import lombok.AllArgsConstructor; 6 | import lombok.Builder; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | 10 | @Builder 11 | @Data 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | public class User implements Serializable { 15 | private long id; 16 | private String name; 17 | private int age; 18 | private Date createTime; 19 | private Date updateTime; 20 | } 21 | -------------------------------------------------------------------------------- /spring-boot-mybatis/src/main/java/com/shumile/springbootmybatis/mapper/UserBuilder.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootmybatis.mapper; 2 | 3 | import org.apache.ibatis.builder.annotation.ProviderMethodResolver; 4 | import org.apache.ibatis.jdbc.SQL; 5 | 6 | public class UserBuilder implements ProviderMethodResolver { 7 | 8 | public String deleteUserSql() { 9 | return new SQL() {{ 10 | DELETE_FROM("user"); 11 | WHERE("ID = ${id}"); 12 | }}.toString(); 13 | } 14 | public static String selectUserById() { 15 | return new SQL() 16 | .SELECT("name,age,create_time,update_time") 17 | .FROM("user") 18 | .WHERE("id = #{id}") 19 | .toString(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /spring-boot-mybatis/src/main/java/com/shumile/springbootmybatis/mapper/UserMapperWithAnnotation.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootmybatis.mapper; 2 | 3 | import com.shumile.springbootmybatis.User; 4 | import org.apache.ibatis.annotations.*; 5 | 6 | /** 7 | * 使用注解方式定义数据库操作接口 8 | */ 9 | @Mapper 10 | public interface UserMapperWithAnnotation { 11 | @Insert("insert into user (name,age, create_time, update_time)" 12 | + "values (#{name},#{age}, now(), now())") 13 | @Options(useGeneratedKeys = true,keyColumn="id", keyProperty="id") 14 | int save(User user); 15 | 16 | @Select("select * from user where id = #{id}") 17 | @Results({ 18 | @Result(id = true, column = "id", property = "id"), 19 | //@Result(column = "create_time", property = "createTime"), 20 | //@Result(column = "update_time", property = "updateTime"), 21 | //配置项map-underscore-to-camel-case = true 可以实现一样的效果 22 | }) 23 | 24 | User findById(@Param("id") Long id); 25 | 26 | } -------------------------------------------------------------------------------- /spring-boot-mybatis/src/main/java/com/shumile/springbootmybatis/mapper/UserMapperWithBuilder.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootmybatis.mapper; 2 | 3 | import com.shumile.springbootmybatis.User; 4 | import org.apache.ibatis.annotations.*; 5 | 6 | /** 7 | * 使用语句构造器方式定义数据库操作接口 8 | */ 9 | @Mapper 10 | public interface UserMapperWithBuilder { 11 | 12 | @SelectProvider(type = UserBuilder.class) 13 | 14 | User selectUserById(long id); 15 | 16 | } -------------------------------------------------------------------------------- /spring-boot-mybatis/src/main/java/com/shumile/springbootmybatis/mapper/UserMapperWithXml.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootmybatis.mapper; 2 | 3 | import com.shumile.springbootmybatis.User; 4 | import org.apache.ibatis.annotations.*; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | /** 9 | * 使用xml方式定义数据库操作接口 10 | */ 11 | public interface UserMapperWithXml { 12 | 13 | List getUserList(Map map); 14 | 15 | } -------------------------------------------------------------------------------- /spring-boot-mybatis/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | #1、数据库连接信息配置 3 | spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8 4 | spring.datasource.username=root 5 | spring.datasource.password=123456 6 | #spring.datasource.type=com.zaxxer.hikari.util.DriverDataSource 7 | 8 | #2、开启下划线的表字段映射为驼峰格式的实体类属性 9 | #mybatis.configuration.map-underscore-to-camel-case=true 10 | 11 | #3、用于指定xml文件的位置(使用xml执行sql语句的方式时) 12 | mybatis.mapper-locations=classpath:mapper/*.xml 13 | 14 | #4、打印sql语句 15 | mybatis.configuration.log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 16 | -------------------------------------------------------------------------------- /spring-boot-mybatis/src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 16 | 17 | -------------------------------------------------------------------------------- /spring-boot-mybatis/src/main/resources/mybatis-configuration.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 12 | 13 | 14 | 15 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /spring-boot-mybatis/src/test/java/com/shumile/springbootmybatis/SpringBootMybatisApplicationTests.java: -------------------------------------------------------------------------------- 1 | // 2 | //package com.shumile.springbootmybatis; 3 | // 4 | //import com.shumile.springbootmybatis.mapper.UserMapperWithAnnotation; 5 | //import org.apache.ibatis.session.SqlSession; 6 | //import org.apache.ibatis.session.SqlSessionFactory; 7 | //import org.junit.Assert; 8 | //import org.junit.jupiter.api.Test; 9 | //import org.springframework.beans.factory.annotation.Autowired; 10 | //import org.springframework.boot.test.context.SpringBootTest; 11 | // 12 | //import java.io.IOException; 13 | //import java.io.Reader; 14 | // 15 | //import org.apache.ibatis.io.Resources; 16 | //import org.apache.ibatis.session.SqlSessionFactoryBuilder; 17 | //@SpringBootTest 18 | //class SpringBootMybatisApplicationTests { 19 | // @Autowired 20 | // private UserMapperWithAnnotation userMapper; 21 | // 22 | // @Test 23 | // public void oneSqlSession() throws IOException { 24 | // //配置文件的名称 25 | // String resource = "mybatis-configuration.xml"; 26 | // //通过Mybatis包中的Resources对象很轻松的获取到配置文件 27 | // Reader reader = Resources.getResourceAsReader(resource); 28 | // //通过SqlSessionFactoryBuilder创建 29 | // SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 30 | // SqlSession sqlSession = null; 31 | // try { 32 | // sqlSession = sqlSessionFactory.openSession(); 33 | // 34 | // // 执行第一次查询 35 | // User user = userMapper.findById(19l); 36 | // 37 | // System.out.println("=============开始同一个 Sqlsession 的第二次查询============"); 38 | // // 同一个 sqlSession 进行第二次查询 39 | // User user2 = userMapper.findById(19l); 40 | // Assert.assertEquals(user2, user); 41 | // System.out.printf("user:"+user); 42 | // } catch (Exception e) { 43 | // e.printStackTrace(); 44 | // } finally { 45 | // if (sqlSession != null) { 46 | // sqlSession.close(); 47 | // } 48 | // } 49 | // } 50 | // 51 | //} 52 | // 53 | -------------------------------------------------------------------------------- /spring-boot-mybatisCache/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /spring-boot-mybatisCache/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/spring-boot-mybatisCache/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-mybatisCache/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /spring-boot-mybatisCache/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.2.5.RELEASE 9 | 10 | 11 | com.shumile 12 | spring-boot-mybatisCache 13 | 0.0.1-SNAPSHOT 14 | spring-boot-mybatisCache 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.mybatis.spring.boot 24 | mybatis-spring-boot-starter 25 | 2.1.2 26 | 27 | 28 | 29 | mysql 30 | mysql-connector-java 31 | runtime 32 | 33 | 34 | org.projectlombok 35 | lombok 36 | true 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-test 43 | test 44 | 45 | 46 | 47 | 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-maven-plugin 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /spring-boot-mybatisCache/src/main/java/com/shumile/springbootmybatis/User.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootmybatis; 2 | import java.io.Serializable; 3 | import java.util.Date; 4 | 5 | import lombok.AllArgsConstructor; 6 | import lombok.Builder; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | 10 | @Builder 11 | @Data 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | public class User implements Serializable { 15 | private long id; 16 | private String name; 17 | private int age; 18 | private Date createTime; 19 | private Date updateTime; 20 | } 21 | -------------------------------------------------------------------------------- /spring-boot-mybatisCache/src/main/java/com/shumile/springbootmybatis/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootmybatis.mapper; 2 | 3 | import com.shumile.springbootmybatis.User; 4 | import org.apache.ibatis.annotations.*; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | /** 9 | * 使用xml方式定义数据库操作接口 10 | */ 11 | public interface UserMapper { 12 | 13 | List getAllUserList(); 14 | 15 | int updateUser(Map map); 16 | 17 | } -------------------------------------------------------------------------------- /spring-boot-mybatisCache/src/main/java/com/shumile/springbootmybatis/mapper/UserMapperWithAnnotation.java: -------------------------------------------------------------------------------- 1 | package com.shumile.springbootmybatis.mapper; 2 | 3 | import com.shumile.springbootmybatis.User; 4 | import org.apache.ibatis.annotations.*; 5 | 6 | /** 7 | * 使用注解方式定义数据库操作接口 8 | */ 9 | @Mapper 10 | public interface UserMapperWithAnnotation { 11 | @Insert("insert into user (name,age, create_time, update_time)" 12 | + "values (#{name},#{age}, now(), now())") 13 | @Options(useGeneratedKeys = true,keyColumn="id", keyProperty="id") 14 | int save(User user); 15 | 16 | @Select("select * from user where id = #{id}") 17 | @Results({ 18 | @Result(id = true, column = "id", property = "id"), 19 | //@Result(column = "create_time", property = "createTime"), 20 | //@Result(column = "update_time", property = "updateTime"), 21 | //配置项map-underscore-to-camel-case = true 可以实现一样的效果 22 | }) 23 | 24 | User findById(@Param("id") Long id); 25 | 26 | } -------------------------------------------------------------------------------- /spring-boot-mybatisCache/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | #1、数据库连接信息配置 3 | spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8 4 | spring.datasource.username=root 5 | spring.datasource.password=123456 6 | #spring.datasource.type=com.zaxxer.hikari.util.DriverDataSource 7 | 8 | #2、开启下划线的表字段映射为驼峰格式的实体类属性 9 | #mybatis.configuration.map-underscore-to-camel-case=true 10 | 11 | #3、用于指定xml文件的位置(使用xml执行sql语句的方式时) 12 | mybatis.mapper-locations=classpath:mapper/*.xml 13 | 14 | #4、打印sql语句 15 | mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl 16 | #一级缓存的范围 17 | mybatis.configuration.local-cache-scope=statement 18 | #二级缓存开关 19 | mybatis.configuration.cache-enabled=true -------------------------------------------------------------------------------- /spring-boot-mybatisCache/src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 17 | 18 | 21 | 22 | update user set age = #{age} 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /spring-boot-mybatisCache/src/main/resources/mybatis-configuration.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /spring-boot-mybatisCache/src/test/java/com/shumile/springbootmybatis/SpringBootMybatisApplicationTests.java: -------------------------------------------------------------------------------- 1 | 2 | package com.shumile.springbootmybatis; 3 | 4 | import org.apache.ibatis.session.SqlSession; 5 | import org.apache.ibatis.session.SqlSessionFactory; 6 | import org.junit.Assert; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | 11 | import java.io.IOException; 12 | import java.io.Reader; 13 | 14 | import org.apache.ibatis.io.Resources; 15 | import org.apache.ibatis.session.SqlSessionFactoryBuilder; 16 | @SpringBootTest 17 | class SpringBootMybatisApplicationTests { 18 | // @Autowired 19 | // private UserMapperWithAnnotation userMapper; 20 | 21 | // @Test 22 | // public void oneSqlSession() throws IOException { 23 | // //配置文件的名称 24 | // String resource = "mybatis-configuration.xml"; 25 | // //通过Mybatis包中的Resources对象很轻松的获取到配置文件 26 | // Reader reader = Resources.getResourceAsReader(resource); 27 | // //通过SqlSessionFactoryBuilder创建 28 | // SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 29 | // SqlSession sqlSession = null; 30 | // try { 31 | // sqlSession = sqlSessionFactory.openSession(); 32 | // 33 | // // 执行第一次查询 34 | // User user = userMapper.findById(19l); 35 | // 36 | // System.out.println("=============开始同一个 Sqlsession 的第二次查询============"); 37 | // // 同一个 sqlSession 进行第二次查询 38 | // User user2 = userMapper.findById(19l); 39 | // Assert.assertEquals(user2, user); 40 | // System.out.printf("user:"+user); 41 | // } catch (Exception e) { 42 | // e.printStackTrace(); 43 | // } finally { 44 | // if (sqlSession != null) { 45 | // sqlSession.close(); 46 | // } 47 | // } 48 | // } 49 | 50 | } 51 | 52 | -------------------------------------------------------------------------------- /springSecurity/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /springSecurity/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/springSecurity/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /springSecurity/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.5/apache-maven-3.8.5-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 3 | -------------------------------------------------------------------------------- /springSecurity/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.0 9 | 10 | 11 | com.wj 12 | springSecurity 13 | 0.0.1-SNAPSHOT 14 | springSecurity 15 | springSecurity Spring Boot 16 | 17 | 1.8 18 | Finchley.RELEASE 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-security 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | org.projectlombok 38 | lombok 39 | true 40 | 41 | 42 | 43 | 44 | mysql 45 | mysql-connector-java 46 | 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-jdbc 51 | 52 | 53 | com.zaxxer 54 | HikariCP 55 | 56 | 57 | 58 | 59 | 60 | com.alibaba 61 | druid-spring-boot-starter 62 | 1.2.9 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | org.springframework.boot 72 | spring-boot-devtools 73 | 74 | 75 | tk.mybatis 76 | mapper-spring-boot-starter 77 | 2.1.5 78 | 79 | 80 | 81 | 82 | 83 | 84 | org.springframework.cloud 85 | spring-cloud-dependencies 86 | ${spring-cloud.version} 87 | pom 88 | import 89 | 90 | 91 | 92 | 93 | 94 | 95 | org.springframework.boot 96 | spring-boot-maven-plugin 97 | 98 | 99 | 100 | org.projectlombok 101 | lombok 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | -------------------------------------------------------------------------------- /springSecurity/src/main/java/com/wj/springSecurity/SpringsecurityOathu2Application.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | @MapperScan("com.wj.springSecurity.reposity") 9 | public class SpringsecurityOathu2Application { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringsecurityOathu2Application.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /springSecurity/src/main/java/com/wj/springSecurity/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | //package com.wj.springSecurity.config; 2 | // 3 | //import com.wj.springSecurity.entity.Permission; 4 | //import com.wj.springSecurity.reposity.PermissionMapper; 5 | //import lombok.extern.slf4j.Slf4j; 6 | //import org.springframework.context.annotation.Bean; 7 | //import org.springframework.context.annotation.Configuration; 8 | //import org.springframework.security.config.annotation.web.builders.HttpSecurity; 9 | //import org.springframework.security.config.annotation.web.builders.WebSecurity; 10 | //import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; 11 | //import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; 12 | //import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 13 | //import org.springframework.security.crypto.password.PasswordEncoder; 14 | //import org.springframework.security.web.SecurityFilterChain; 15 | // 16 | //import javax.annotation.Resource; 17 | //import java.util.List; 18 | // 19 | //@Configuration 20 | //@Slf4j 21 | //public class SecurityConfig { 22 | // 23 | // @Resource 24 | // private PermissionMapper permissionMapper; 25 | // 26 | // @Bean 27 | // public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 28 | // ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry 29 | // authorizeRequests = http.csrf().disable().authorizeRequests(); 30 | //// 方式二:配置来源于数据库 31 | //// 1.查询到所有的权限 32 | // List allPermission = permissionMapper.findAllPermission(); 33 | //// 2.分别添加权限规则 34 | // allPermission.forEach((p -> { 35 | // authorizeRequests.antMatchers(p.getUrl()).hasAnyAuthority(p.getName()) ; 36 | // })); 37 | // 38 | // authorizeRequests.antMatchers("/**").fullyAuthenticated() 39 | // .anyRequest().authenticated().and().formLogin(); 40 | // return http.build(); 41 | // } 42 | // 43 | // @Bean 44 | // WebSecurityCustomizer webSecurityCustomizer() { 45 | // return new WebSecurityCustomizer() { 46 | // @Override 47 | // public void customize(WebSecurity web) { 48 | // web.ignoring().antMatchers("/hello"); 49 | // web.ignoring().antMatchers("/css/**", "/js/**"); 50 | // } 51 | // }; 52 | // } 53 | // 54 | // @Bean 55 | // public PasswordEncoder passwordEncoder(){ 56 | // return new BCryptPasswordEncoder(); 57 | // } 58 | // 59 | //} 60 | -------------------------------------------------------------------------------- /springSecurity/src/main/java/com/wj/springSecurity/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.config; 2 | 3 | import com.wj.springSecurity.entity.User; 4 | import com.wj.springSecurity.reposity.PermissionMapper; 5 | import com.wj.springSecurity.service.UserService; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 12 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 13 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 14 | import org.springframework.security.crypto.password.PasswordEncoder; 15 | import javax.annotation.Resource; 16 | 17 | @Configuration 18 | @EnableWebSecurity 19 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 20 | @Resource 21 | private UserService userService; 22 | 23 | @Resource 24 | private PermissionMapper permissionMapper; 25 | 26 | /** 27 | * 将用户配置在内存或者mysql中(可登录用户,包括用户名、密码和角色) 28 | * @param auth 29 | * @throws Exception 30 | */ 31 | @Override 32 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 33 | // 方式一:写到内存 34 | auth.inMemoryAuthentication() 35 | .withUser("admin").password(passwordEncoder().encode("123456")).authorities("admin") 36 | .and() 37 | .withUser("user").password(passwordEncoder().encode("123456")).authorities("common"); 38 | // 方式二:来源于数据库 39 | auth.userDetailsService(userService).passwordEncoder(passwordEncoder()); 40 | 41 | // System.out.println("密码:"+new BCryptPasswordEncoder().encode("123456")); 42 | } 43 | 44 | /** 45 | * 登录处理-配置对应用户所拥有的权限(url、authority对应的所有关系) 46 | * @param http 47 | * @throws Exception 48 | */ 49 | @Override 50 | protected void configure(HttpSecurity http) throws Exception { 51 | 52 | // 方式一:写死的方式 53 | http.authorizeRequests(). 54 | antMatchers("/user/common").hasAnyAuthority("admin") 55 | .antMatchers("/user/admin").hasAnyAuthority("common") 56 | .antMatchers("/user/common").hasAnyAuthority("common") 57 | .antMatchers("/**").fullyAuthenticated() 58 | .anyRequest().authenticated() 59 | .and().formLogin(); 60 | 61 | // 方式二:配置来源于数据库 62 | // ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry 63 | // authorizeRequests = http.csrf().disable().authorizeRequests(); 64 | // 1.查询到所有的权限 65 | // List allPermission = permissionMapper.findAllPermission(); 66 | // 2.分别添加权限规则 67 | // allPermission.forEach((p -> { 68 | // authorizeRequests.antMatchers(p.getUrl()).hasAnyAuthority(p.getName()) ; 69 | // })); 70 | // 71 | // authorizeRequests.antMatchers("/**").fullyAuthenticated() 72 | // .anyRequest().authenticated().and().formLogin(); 73 | 74 | 75 | } 76 | 77 | /** 78 | * 忽略拦截处理 79 | * @param web 80 | * @throws Exception 81 | */ 82 | @Override 83 | public void configure(WebSecurity web) throws Exception { 84 | // 设置拦截忽略url - 会直接过滤该url - 将不会经过Spring Security过滤器链 85 | web.ignoring().antMatchers("/getUserInfo"); 86 | // 设置拦截忽略文件夹,可以对静态资源放行 87 | web.ignoring().antMatchers("/css/**", "/js/**"); 88 | } 89 | 90 | /** 91 | * 密码解密类 92 | * @return 93 | */ 94 | @Bean 95 | public PasswordEncoder passwordEncoder(){ 96 | return new BCryptPasswordEncoder(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /springSecurity/src/main/java/com/wj/springSecurity/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | @RequestMapping("/user") 9 | public class UserController { 10 | 11 | @GetMapping("/common") 12 | public String common() { 13 | return "hello~ common"; 14 | } 15 | 16 | @GetMapping("/admin") 17 | public String admin() { 18 | return "hello~ admin"; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /springSecurity/src/main/java/com/wj/springSecurity/entity/Permission.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.entity; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Permission { 7 | private Integer id; 8 | 9 | private String url; 10 | 11 | private String name; 12 | 13 | private String description; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /springSecurity/src/main/java/com/wj/springSecurity/entity/Role.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.entity; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Role { 7 | private Integer id; 8 | private String name; 9 | } 10 | -------------------------------------------------------------------------------- /springSecurity/src/main/java/com/wj/springSecurity/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.entity; 2 | 3 | import lombok.Data; 4 | import org.springframework.security.core.GrantedAuthority; 5 | import org.springframework.security.core.userdetails.UserDetails; 6 | 7 | import java.util.ArrayList; 8 | import java.util.Collection; 9 | import java.util.List; 10 | 11 | @Data 12 | public class User implements UserDetails { 13 | private Integer id; 14 | private String username; 15 | private String password; 16 | private String role; 17 | 18 | // 用户所有权限 19 | private List authorities = new ArrayList(); 20 | 21 | public Collection getAuthorities() { 22 | 23 | return authorities; 24 | } 25 | 26 | @Override 27 | public boolean isAccountNonExpired() { 28 | return true; 29 | } 30 | 31 | @Override 32 | public boolean isAccountNonLocked() { 33 | return true; 34 | } 35 | 36 | @Override 37 | public boolean isCredentialsNonExpired() { 38 | return true; 39 | } 40 | 41 | @Override 42 | public boolean isEnabled() { 43 | return true; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /springSecurity/src/main/java/com/wj/springSecurity/reposity/PermissionMapper.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.reposity; 2 | 3 | import com.wj.springSecurity.entity.Permission; 4 | import org.apache.ibatis.annotations.Select; 5 | 6 | import java.util.List; 7 | 8 | public interface PermissionMapper { 9 | 10 | 11 | /** 12 | * 查询用户的权限根据用户查询权限 13 | * 14 | * @return 15 | */ 16 | @Select("select * from permission") 17 | List findAllPermission(); 18 | } 19 | -------------------------------------------------------------------------------- /springSecurity/src/main/java/com/wj/springSecurity/reposity/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.reposity; 2 | 3 | import com.wj.springSecurity.entity.Permission; 4 | import com.wj.springSecurity.entity.User; 5 | import org.apache.ibatis.annotations.Param; 6 | import org.apache.ibatis.annotations.Select; 7 | 8 | import java.util.List; 9 | 10 | public interface UserMapper { 11 | 12 | /** 13 | * 根据用户名称查询 14 | * 15 | * @param userName 16 | * @return 17 | */ 18 | @Select(" select * from user where username = #{userName}") 19 | User findByUsername(@Param("userName") String userName); 20 | 21 | /** 22 | * 查询用户的权限根据用户查询权限 23 | * 24 | * @param userName 25 | * @return 26 | */ 27 | @Select(" SELECT d.*\n" + 28 | "from user a,user_role b,role_permission c,permission d\n" + 29 | "WHERE \n" + 30 | "a.id = b.user_id\n" + 31 | "and b.role_id = c.role_id\n" + 32 | "and c.permission_id = d.id\n" + 33 | "and \n" + 34 | "a.username= #{userName};") 35 | List findPermissionByUsername(@Param("userName") String userName); 36 | } 37 | -------------------------------------------------------------------------------- /springSecurity/src/main/java/com/wj/springSecurity/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.service; 2 | 3 | import com.wj.springSecurity.entity.User; 4 | import org.springframework.security.core.userdetails.UserDetailsService; 5 | 6 | public interface UserService extends UserDetailsService { 7 | 8 | 9 | } -------------------------------------------------------------------------------- /springSecurity/src/main/java/com/wj/springSecurity/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.service; 2 | 3 | import com.wj.springSecurity.entity.Permission; 4 | import com.wj.springSecurity.entity.User; 5 | import com.wj.springSecurity.reposity.UserMapper; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.security.core.GrantedAuthority; 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 11 | import org.springframework.stereotype.Service; 12 | 13 | import javax.annotation.Resource; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | @Slf4j 18 | @Service 19 | public class UserServiceImpl implements UserService { 20 | 21 | @Resource 22 | private UserMapper userMapper; 23 | 24 | @Override 25 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 26 | // 1.根据用户名称查询到user用户
 27 | User userDetails = userMapper.findByUsername(username); 28 | if (userDetails == null) { 29 | return null; 30 | } 31 | // 2.查询该用户对应的权限
 32 | List permissionList = userMapper.findPermissionByUsername(username); 33 | List grantedAuthorities = new ArrayList<>(); 34 | permissionList.forEach((a) -> grantedAuthorities.add(new SimpleGrantedAuthority(a.getName()))); 35 | log.info(">>permissionList:{}<<", permissionList); 36 | // 设置权限
 37 | userDetails.setAuthorities(grantedAuthorities); 38 | return userDetails; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /springSecurity/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8082 3 | 4 | spring: 5 | datasource: 6 | url: jdbc:mysql://localhost:3306/security_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false 7 | username: root 8 | password: 123456 9 | # driver-class-name: com.mysql.jdbc.Driver 10 | # druid: 11 | # initialSize: 1 12 | # minIdle: 1 13 | # maxActive: 50 14 | # maxWait: 6000 15 | # timeBetweenEvictionRunsMillis: 6000 16 | # minEvictableIdleTimeMillis: 30000 17 | # testWhileIdle: true 18 | # testOnBorrow: true 19 | # testOnReturn: true 20 | # validationQuery: SELECT 1 from dual 21 | # connectionProperties: config.decrypt=false -------------------------------------------------------------------------------- /springSecurity/src/test/java/com/wj/springSecurity/SpringsecurityOathu2ApplicationTests.java: -------------------------------------------------------------------------------- 1 | //package com.wj.springSecurity; 2 | // 3 | //import org.junit.jupiter.api.Test; 4 | //import org.springframework.boot.test.context.SpringBootTest; 5 | // 6 | //@SpringBootTest 7 | //class SpringsecurityOathu2ApplicationTests { 8 | // 9 | // @Test 10 | // void contextLoads() { 11 | // } 12 | // 13 | //} 14 | -------------------------------------------------------------------------------- /springSecurity/table_and_data.sql: -------------------------------------------------------------------------------- 1 | -- ---------------------------- 2 | -- Table structure for permission 3 | -- ---------------------------- 4 | DROP TABLE IF EXISTS `permission`; 5 | CREATE TABLE `permission` ( 6 | `id` bigint(11) NOT NULL AUTO_INCREMENT, 7 | `url` varchar(255) NOT NULL, 8 | `name` varchar(255) NOT NULL, 9 | `description` varchar(255) DEFAULT NULL, 10 | `pid` bigint(11) NOT NULL, 11 | PRIMARY KEY (`id`) 12 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 13 | 14 | -- ---------------------------- 15 | -- Records of permission 16 | -- ---------------------------- 17 | BEGIN; 18 | INSERT INTO `permission` VALUES (1, '/user/common', 'common', NULL, 0); 19 | INSERT INTO `permission` VALUES (2, '/user/admin', 'admin', NULL, 0); 20 | COMMIT; 21 | 22 | -- ---------------------------- 23 | -- Table structure for role 24 | -- ---------------------------- 25 | DROP TABLE IF EXISTS `role`; 26 | CREATE TABLE `role` ( 27 | `id` bigint(11) NOT NULL AUTO_INCREMENT, 28 | `name` varchar(255) NOT NULL, 29 | PRIMARY KEY (`id`) 30 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 31 | 32 | -- ---------------------------- 33 | -- Records of role 34 | -- ---------------------------- 35 | BEGIN; 36 | INSERT INTO `role` VALUES (1, 'USER'); 37 | INSERT INTO `role` VALUES (2, 'ADMIN'); 38 | COMMIT; 39 | 40 | -- ---------------------------- 41 | -- Table structure for role_permission 42 | -- ---------------------------- 43 | DROP TABLE IF EXISTS `role_permission`; 44 | CREATE TABLE `role_permission` ( 45 | `id` int(11) NOT NULL AUTO_INCREMENT, 46 | `role_id` bigint(11) NOT NULL, 47 | `permission_id` bigint(11) NOT NULL, 48 | PRIMARY KEY (`id`) 49 | ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; 50 | 51 | -- ---------------------------- 52 | -- Records of role_permission 53 | -- ---------------------------- 54 | BEGIN; 55 | INSERT INTO `role_permission` VALUES (1, 1, 1); 56 | INSERT INTO `role_permission` VALUES (2, 2, 1); 57 | INSERT INTO `role_permission` VALUES (3, 2, 2); 58 | COMMIT; 59 | 60 | -- ---------------------------- 61 | -- Table structure for user 62 | -- ---------------------------- 63 | DROP TABLE IF EXISTS `user`; 64 | CREATE TABLE `user` ( 65 | `id` bigint(11) NOT NULL AUTO_INCREMENT, 66 | `username` varchar(255) NOT NULL, 67 | `password` varchar(255) NOT NULL, 68 | PRIMARY KEY (`id`) 69 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 70 | 71 | -- ---------------------------- 72 | -- Records of user 73 | -- ---------------------------- 74 | BEGIN; 75 | INSERT INTO `user` VALUES (1, 'user', '$2a$10$4zd/aj2BNJhuM5PIs5BupO8tiN2yikzP7JMzNaq1fXhcXUefWCOF2'); 76 | INSERT INTO `user` VALUES (2, 'admin', '$2a$10$4zd/aj2BNJhuM5PIs5BupO8tiN2yikzP7JMzNaq1fXhcXUefWCOF2'); 77 | COMMIT; 78 | 79 | -- ---------------------------- 80 | -- Table structure for user_role 81 | -- ---------------------------- 82 | DROP TABLE IF EXISTS `user_role`; 83 | CREATE TABLE `user_role` ( 84 | `id` int(11) NOT NULL AUTO_INCREMENT, 85 | `user_id` bigint(11) NOT NULL, 86 | `role_id` bigint(11) NOT NULL, 87 | PRIMARY KEY (`id`) 88 | ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; 89 | 90 | -- ---------------------------- 91 | -- Records of user_role 92 | -- ---------------------------- 93 | BEGIN; 94 | INSERT INTO `user_role` VALUES (1, 1, 1); 95 | INSERT INTO `user_role` VALUES (3, 2, 2); 96 | COMMIT; 97 | -------------------------------------------------------------------------------- /springSecurityJwt/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /springSecurityJwt/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/springSecurityJwt/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /springSecurityJwt/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.5/apache-maven-3.8.5-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 3 | -------------------------------------------------------------------------------- /springSecurityJwt/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.0 9 | 10 | 11 | com.wj 12 | springSecurity 13 | 0.0.1-SNAPSHOT 14 | springSecurity 15 | springSecurity Spring Boot 16 | 17 | 1.8 18 | 0.10.6 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-security 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | 33 | 34 | org.projectlombok 35 | lombok 36 | true 37 | 38 | 39 | 40 | 41 | mysql 42 | mysql-connector-java 43 | 44 | 45 | 46 | com.alibaba 47 | druid-spring-boot-starter 48 | 1.2.9 49 | 50 | 51 | 52 | io.jsonwebtoken 53 | jjwt-api 54 | ${jwt.version} 55 | 56 | 57 | 58 | com.auth0 59 | java-jwt 60 | 3.12.1 61 | 62 | 63 | 64 | io.jsonwebtoken 65 | jjwt-impl 66 | ${jwt.version} 67 | runtime 68 | 69 | 70 | 71 | io.jsonwebtoken 72 | jjwt-jackson 73 | ${jwt.version} 74 | 75 | 76 | 77 | org.springframework.boot 78 | spring-boot-devtools 79 | 80 | 81 | tk.mybatis 82 | mapper-spring-boot-starter 83 | 2.1.5 84 | 85 | 86 | cn.hutool 87 | hutool-all 88 | 5.8.4.M1 89 | 90 | 91 | 92 | 93 | 94 | 95 | org.springframework.boot 96 | spring-boot-maven-plugin 97 | 98 | 99 | 100 | org.projectlombok 101 | lombok 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/SpringsecurityJwtApplication.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | @MapperScan("com.wj.springSecurity.jwt.reposity") 9 | public class SpringsecurityJwtApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringsecurityJwtApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.config; 2 | 3 | import com.wj.springSecurity.jwt.entity.Permission; 4 | import com.wj.springSecurity.jwt.filter.JwtAuthenticationFilter; 5 | import com.wj.springSecurity.jwt.reposity.PermissionMapper; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; 11 | import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; 12 | import org.springframework.security.config.http.SessionCreationPolicy; 13 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 14 | import org.springframework.security.crypto.password.PasswordEncoder; 15 | import org.springframework.security.web.SecurityFilterChain; 16 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 17 | 18 | import javax.annotation.Resource; 19 | import java.util.List; 20 | 21 | /** 22 | * 新版本 Spring Security 的认证权限配置类写法 23 | */ 24 | @Configuration 25 | @Slf4j 26 | public class SecurityConfig { 27 | 28 | @Resource 29 | private PermissionMapper permissionMapper; 30 | //JWT 的认证过滤器 31 | @Resource 32 | private JwtAuthenticationFilter jwtAuthenticationFilter; 33 | 34 | @Bean 35 | public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 36 | 37 | ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry 38 | authorizeRequests = http.csrf().disable().authorizeRequests(); 39 | // 1.查询到所有的权限 40 | List allPermission = permissionMapper.findAllPermission(); 41 | // 2.分别添加权限规则 42 | allPermission.forEach((p -> { 43 | authorizeRequests.antMatchers(p.getUrl()).hasAnyAuthority(p.getName()) ; 44 | })); 45 | 46 | authorizeRequests.and() 47 | // 配置为 Spring Security 不创建使用 session 48 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 49 | .and() 50 | .authorizeRequests() 51 | .antMatchers("/**").fullyAuthenticated() 52 | .antMatchers("/authenticate").permitAll() 53 | .anyRequest().authenticated(); 54 | //配置认证过滤器 jwtAuthenticationFilter 55 | http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); 56 | return http.build(); 57 | } 58 | 59 | /** 60 | * 资源放行配置 61 | * @return 62 | */ 63 | @Bean 64 | WebSecurityCustomizer webSecurityCustomizer() { 65 | return web -> { 66 | web.ignoring().antMatchers("/hello"); 67 | web.ignoring().antMatchers("/login"); 68 | //获取 token 的接口放行 69 | web.ignoring().antMatchers("/authenticate"); 70 | web.ignoring().antMatchers("/css/**", "/js/**"); 71 | }; 72 | } 73 | 74 | @Bean 75 | public PasswordEncoder passwordEncoder(){ 76 | return new BCryptPasswordEncoder(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/controller/JwtAuthenticationController.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.controller; 2 | 3 | import cn.hutool.core.util.StrUtil; 4 | import com.wj.springSecurity.jwt.entity.User; 5 | import com.wj.springSecurity.jwt.service.JwtService; 6 | import com.wj.springSecurity.jwt.service.UserService; 7 | import com.wj.springSecurity.jwt.utils.MD5Util; 8 | import com.wj.springSecurity.jwt.vo.ResponseResult; 9 | import com.wj.springSecurity.jwt.vo.UserVo; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import javax.annotation.Resource; 14 | import java.util.UUID; 15 | 16 | @RestController 17 | @CrossOrigin 18 | public class JwtAuthenticationController { 19 | 20 | @Resource 21 | private UserService userService; 22 | 23 | @Resource 24 | private JwtService jwtService; 25 | 26 | /** 27 | * 登录接口 - 用于生成 token 28 | * @param username 用户名 29 | * @param password 密码 30 | * @return 31 | * @throws Exception 32 | */ 33 | @PostMapping("/authenticate") 34 | public ResponseResult login(String username, String password) throws Exception { 35 | //1-校验用户名密码是否为空 36 | if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){ 37 | throw new Exception("用户名或密码不能为空!"); 38 | } 39 | 40 | // 2-根据用户查询用户是否存在 41 | UserDetails user = userService.loadUserByUsername(username); 42 | if (user == null){ 43 | throw new Exception("用户名或密码有误!"); 44 | } 45 | //3-验证用户名密码 46 | password = MD5Util.md5slat(password); 47 | if (!password.equalsIgnoreCase(user.getPassword())){ 48 | throw new Exception("用户名或密码有误!"); 49 | } 50 | 51 | UserVo userVo = UserVo.builder().build(); 52 | userVo.setUsername(username); 53 | userVo.setPassword(password); 54 | userVo.setAuthorities(user.getAuthorities()); 55 | //4- 生成 token 56 | String token = jwtService.createToken(userVo); 57 | userVo.setToken(token); 58 | userVo.setRefreshToken(UUID.randomUUID().toString()); 59 | 60 | return new ResponseResult(userVo); 61 | } 62 | } -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | @RequestMapping("/user") 9 | public class UserController { 10 | 11 | @GetMapping("/common") 12 | public String common() { 13 | return "hello~ common"; 14 | } 15 | 16 | @GetMapping("/admin") 17 | public String admin() { 18 | return "hello~ admin"; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/entity/Permission.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.entity; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Permission { 7 | private Integer id; 8 | 9 | private String url; 10 | 11 | private String name; 12 | 13 | private String description; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/entity/Role.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.entity; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Role { 7 | private Integer id; 8 | private String name; 9 | } 10 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.entity; 2 | 3 | import lombok.Data; 4 | import org.springframework.security.core.GrantedAuthority; 5 | import org.springframework.security.core.userdetails.UserDetails; 6 | 7 | import java.util.ArrayList; 8 | import java.util.Collection; 9 | import java.util.List; 10 | 11 | @Data 12 | public class User implements UserDetails { 13 | private Long id; 14 | private String username; 15 | private String password; 16 | private String role; 17 | // 用户所有权限 18 | private List authorities = new ArrayList(); 19 | 20 | public Collection getAuthorities() { 21 | 22 | return authorities; 23 | } 24 | 25 | @Override 26 | public boolean isAccountNonExpired() { 27 | return true; 28 | } 29 | 30 | @Override 31 | public boolean isAccountNonLocked() { 32 | return true; 33 | } 34 | 35 | @Override 36 | public boolean isCredentialsNonExpired() { 37 | return true; 38 | } 39 | 40 | @Override 41 | public boolean isEnabled() { 42 | return true; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/filter/JwtAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.filter; 2 | 3 | 4 | import cn.hutool.core.util.StrUtil; 5 | import com.wj.springSecurity.jwt.service.JwtService; 6 | import com.wj.springSecurity.jwt.service.UserService; 7 | import com.wj.springSecurity.jwt.vo.ResponseResult; 8 | import io.jsonwebtoken.ExpiredJwtException; 9 | import io.jsonwebtoken.MalformedJwtException; 10 | import io.jsonwebtoken.UnsupportedJwtException; 11 | import lombok.extern.slf4j.Slf4j; 12 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 13 | import org.springframework.security.core.Authentication; 14 | import org.springframework.security.core.context.SecurityContextHolder; 15 | import org.springframework.security.core.userdetails.UserDetails; 16 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 17 | import org.springframework.stereotype.Component; 18 | import org.springframework.web.filter.OncePerRequestFilter; 19 | 20 | 21 | import javax.annotation.Resource; 22 | import javax.servlet.FilterChain; 23 | import javax.servlet.ServletException; 24 | import javax.servlet.http.HttpServletRequest; 25 | import javax.servlet.http.HttpServletResponse; 26 | import java.io.IOException; 27 | 28 | /** 29 | * JWT 认证过滤器 30 | */ 31 | @Slf4j 32 | @Component 33 | public class JwtAuthenticationFilter extends OncePerRequestFilter { 34 | 35 | @Resource 36 | private JwtService jwtService; 37 | 38 | @Override 39 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 40 | throws ServletException, IOException { 41 | try { 42 | //1-获取 token 43 | String token = request.getHeader("Authorization"); 44 | if (StrUtil.isBlank(token)) { 45 | //放行,会自动执行后面的过滤器 46 | logger.info("请求头不含 JWT token 或者 token 的值为空,调用下个过滤器"); 47 | filterChain.doFilter(request,response); 48 | return; 49 | } 50 | //2-获取认证信息 51 | Authentication authentication = jwtService.getAuthentication(token); 52 | //3-设置用户验证对象 53 | SecurityContextHolder.getContext().setAuthentication(authentication); 54 | } catch (MalformedJwtException | ExpiredJwtException | UnsupportedJwtException e) { 55 | SecurityContextHolder.getContext().setAuthentication(null); 56 | } finally{ 57 | filterChain.doFilter(request, response); 58 | } 59 | } 60 | 61 | 62 | } -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/reposity/PermissionMapper.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.reposity; 2 | 3 | import com.wj.springSecurity.jwt.entity.Permission; 4 | import org.apache.ibatis.annotations.Select; 5 | 6 | import java.util.List; 7 | 8 | public interface PermissionMapper { 9 | 10 | 11 | /** 12 | * 查询用户的权限根据用户查询权限 13 | * 14 | * @return 15 | */ 16 | @Select("select * from permission") 17 | List findAllPermission(); 18 | } 19 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/reposity/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.reposity; 2 | 3 | import com.wj.springSecurity.jwt.entity.Permission; 4 | import com.wj.springSecurity.jwt.entity.User; 5 | import org.apache.ibatis.annotations.Param; 6 | import org.apache.ibatis.annotations.Select; 7 | 8 | import java.util.List; 9 | 10 | public interface UserMapper { 11 | 12 | /** 13 | * 根据用户名称查询 14 | * 15 | * @param userName 16 | * @return 17 | */ 18 | @Select("select * from user where username = #{userName}") 19 | User findByUsername(@Param("userName") String userName); 20 | 21 | /** 22 | * 查询用户的权限根据用户查询权限 23 | * 24 | * @param userName 25 | * @return 26 | */ 27 | @Select(" SELECT d.*\n" + 28 | "from user a,user_role b,role_permission c,permission d\n" + 29 | "WHERE \n" + 30 | "a.id = b.user_id\n" + 31 | "and b.role_id = c.role_id\n" + 32 | "and c.permission_id = d.id\n" + 33 | "and \n" + 34 | "a.username= #{userName};") 35 | List findPermissionByUsername(@Param("userName") String userName); 36 | } 37 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/service/JwtService.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.service; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.auth0.jwt.JWTVerifier; 5 | import com.auth0.jwt.algorithms.Algorithm; 6 | import com.auth0.jwt.exceptions.JWTDecodeException; 7 | import com.auth0.jwt.interfaces.DecodedJWT; 8 | import com.wj.springSecurity.jwt.vo.ResponseResult; 9 | import com.wj.springSecurity.jwt.vo.UserVo; 10 | import io.jsonwebtoken.*; 11 | import io.jsonwebtoken.io.Decoders; 12 | import io.jsonwebtoken.security.Keys; 13 | import lombok.extern.slf4j.Slf4j; 14 | import org.springframework.beans.factory.InitializingBean; 15 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 16 | import org.springframework.security.core.Authentication; 17 | import org.springframework.security.core.GrantedAuthority; 18 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 19 | import org.springframework.security.core.userdetails.User; 20 | import org.springframework.stereotype.Service; 21 | 22 | import java.security.Key; 23 | import java.util.Arrays; 24 | import java.util.Collection; 25 | import java.util.Date; 26 | import java.util.stream.Collectors; 27 | 28 | @Slf4j 29 | @Service 30 | public class JwtService implements InitializingBean{ 31 | 32 | private static final String KEY = "wangjienihaowangjienihaowangjienihaowangjienihao"; 33 | 34 | private static final String ISSUER = "jiege"; 35 | 36 | private static final String AUTHORITIES_KEY = "auth"; 37 | 38 | public static final Long TOKEN_EXSPIRE_TIME = 1000 * 60 * 60 * 10L; 39 | 40 | private Key key; 41 | 42 | 43 | /** 44 | * 创建 token 45 | * @param userVo 用户对象 46 | * @return token 47 | */ 48 | public String createToken(UserVo userVo) { 49 | String authorities = userVo.getAuthorities().stream() 50 | .map(GrantedAuthority::getAuthority) 51 | .collect(Collectors.joining(",")); 52 | 53 | long now = (new Date()).getTime(); 54 | 55 | return Jwts.builder() 56 | .setSubject(userVo.getUsername()) 57 | .claim(AUTHORITIES_KEY, authorities) 58 | .setExpiration(new Date(now + TOKEN_EXSPIRE_TIME)) 59 | .signWith(key, SignatureAlgorithm.HS256) 60 | .compact(); 61 | } 62 | 63 | /** 64 | * 获取认证过的token对应的信息,包括用户以及用户对应的权限 65 | * @param token 66 | * @return 67 | */ 68 | public Authentication getAuthentication(String token) { 69 | // 1-根据 token 和秘钥,解析出 JWT 的 claims 对象 70 | Claims claims = 71 | Jwts.parser() 72 | .setSigningKey(KEY) 73 | .parseClaimsJws(token) 74 | .getBody(); 75 | // 2-获取权限信息,并转换为集合类型 76 | Collection authorities = 77 | Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) 78 | .map(SimpleGrantedAuthority::new) 79 | .collect(Collectors.toList()); 80 | //3-得到用户对象 principal 81 | User principal = new User(claims.getSubject(), "", authorities); 82 | //4-得到认证 token 对象(UsernamePasswordAuthenticationToken 实现了 Authentication 接口,表示是通过用户名密码认证过的 token 认证信息) 83 | return new UsernamePasswordAuthenticationToken(principal, token, authorities); 84 | 85 | } 86 | 87 | @Override 88 | public void afterPropertiesSet() { 89 | byte[] keyBytes = Decoders.BASE64.decode(KEY); 90 | this.key = Keys.hmacShaKeyFor(keyBytes); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.service; 2 | 3 | import com.wj.springSecurity.jwt.entity.User; 4 | import org.springframework.security.core.userdetails.UserDetailsService; 5 | 6 | public interface UserService extends UserDetailsService { 7 | 8 | User findByUsername(String username); 9 | 10 | } -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.service; 2 | 3 | import com.wj.springSecurity.jwt.entity.Permission; 4 | import com.wj.springSecurity.jwt.entity.User; 5 | import com.wj.springSecurity.jwt.reposity.UserMapper; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.security.core.GrantedAuthority; 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 11 | import org.springframework.stereotype.Service; 12 | 13 | import javax.annotation.Resource; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | @Slf4j 18 | @Service 19 | public class UserServiceImpl implements UserService { 20 | 21 | @Resource 22 | private UserMapper userMapper; 23 | 24 | @Override 25 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 26 | // 1.根据用户名称查询到user用户
 27 | User userDetails = userMapper.findByUsername(username); 28 | if (userDetails == null) { 29 | return null; 30 | } 31 | // 2.查询该用户对应的权限
 32 | List permissionList = userMapper.findPermissionByUsername(username); 33 | List grantedAuthorities = new ArrayList<>(); 34 | permissionList.forEach((a) -> grantedAuthorities.add(new SimpleGrantedAuthority(a.getName()))); 35 | log.info(">>permissionList:{}<<", permissionList); 36 | // 设置权限
 37 | userDetails.setAuthorities(grantedAuthorities); 38 | return userDetails; 39 | } 40 | 41 | @Override 42 | public User findByUsername(String username) { 43 | return userMapper.findByUsername(username); 44 | 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/utils/MD5Util.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.utils; 2 | 3 | import io.jsonwebtoken.SignatureAlgorithm; 4 | import io.jsonwebtoken.security.Keys; 5 | 6 | import java.math.BigInteger; 7 | import java.nio.charset.StandardCharsets; 8 | import java.security.MessageDigest; 9 | 10 | public class MD5Util { 11 | public MD5Util() { 12 | } 13 | 14 | public static String md5(String str) { 15 | try { 16 | MessageDigest md5 = MessageDigest.getInstance("MD5"); 17 | md5.update(str.getBytes(StandardCharsets.UTF_8)); 18 | return bytesToHex(md5.digest()); 19 | } catch (Exception var2) { 20 | throw new RuntimeException(var2); 21 | } 22 | } 23 | 24 | public static String md5slat(String str){ 25 | return MD5Util.md5(MD5Util.md5("jiege"+str+"123")); 26 | } 27 | 28 | public static String bytesToHex(byte[] bytes) { 29 | BigInteger bigInt = new BigInteger(1, bytes); 30 | 31 | String hashtext; 32 | for(hashtext = bigInt.toString(16); hashtext.length() < 32; hashtext = "0" + hashtext) { 33 | } 34 | 35 | return hashtext; 36 | } 37 | 38 | public static void main(String[] args) { 39 | System.out.println(md5slat("123456")); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/vo/ResponseResult.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.vo; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | 6 | @Data 7 | @NoArgsConstructor 8 | public class ResponseResult { 9 | 10 | private Integer status = 1; // 1 成功 -1,失败 11 | 12 | private String message = "成功!"; 13 | 14 | private Object data; 15 | 16 | 17 | public ResponseResult(Integer status, String message){ 18 | this.status = status; 19 | this.message = message; 20 | } 21 | 22 | public ResponseResult(Object data){ 23 | this.data = data; 24 | } 25 | 26 | public ResponseResult(Integer status, String message,Object data){ 27 | this(status,message); 28 | this.data = data; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/java/com/wj/springSecurity/jwt/vo/UserVo.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurity.jwt.vo; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | import org.springframework.security.core.GrantedAuthority; 6 | 7 | import java.io.Serializable; 8 | import java.util.ArrayList; 9 | import java.util.Collection; 10 | import java.util.List; 11 | 12 | @Data 13 | @Builder 14 | public class UserVo implements Serializable { 15 | 16 | private Long id; 17 | 18 | private String username; 19 | 20 | private String password; 21 | 22 | private String token; 23 | 24 | private String refreshToken; 25 | 26 | // 用户所有权限 27 | private List authorities = new ArrayList(); 28 | 29 | public Collection getAuthorities() { 30 | 31 | return authorities; 32 | } 33 | 34 | public void setAuthorities(Collection authorities) { 35 | this.authorities = (List) authorities; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /springSecurityJwt/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8082 3 | 4 | spring: 5 | datasource: 6 | url: jdbc:mysql://localhost:3306/security_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false 7 | username: root 8 | password: 123456 9 | # driver-class-name: com.mysql.jdbc.Driver 10 | # druid: 11 | # initialSize: 1 12 | # minIdle: 1 13 | # maxActive: 50 14 | # maxWait: 6000 15 | # timeBetweenEvictionRunsMillis: 6000 16 | # minEvictableIdleTimeMillis: 30000 17 | # testWhileIdle: true 18 | # testOnBorrow: true 19 | # testOnReturn: true 20 | # validationQuery: SELECT 1 from dual 21 | # connectionProperties: config.decrypt=false -------------------------------------------------------------------------------- /springSecurityJwt/src/test/java/com/wj/springSecurity/SpringsecurityOathu2ApplicationTests.java: -------------------------------------------------------------------------------- 1 | //package com.wj.springSecurity; 2 | // 3 | //import org.junit.jupiter.api.Test; 4 | //import org.springframework.boot.test.context.SpringBootTest; 5 | // 6 | //@SpringBootTest 7 | //class SpringsecurityOathu2ApplicationTests { 8 | // 9 | // @Test 10 | // void contextLoads() { 11 | // } 12 | // 13 | //} 14 | -------------------------------------------------------------------------------- /springSecurityJwt/table_and_data.sql: -------------------------------------------------------------------------------- 1 | -- ---------------------------- 2 | -- Table structure for permission 3 | -- ---------------------------- 4 | DROP TABLE IF EXISTS `permission`; 5 | CREATE TABLE `permission` ( 6 | `id` bigint(11) NOT NULL AUTO_INCREMENT, 7 | `url` varchar(255) NOT NULL, 8 | `name` varchar(255) NOT NULL, 9 | `description` varchar(255) DEFAULT NULL, 10 | `pid` bigint(11) NOT NULL, 11 | PRIMARY KEY (`id`) 12 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 13 | 14 | -- ---------------------------- 15 | -- Records of permission 16 | -- ---------------------------- 17 | BEGIN; 18 | INSERT INTO `permission` VALUES (1, '/user/common', 'common', NULL, 0); 19 | INSERT INTO `permission` VALUES (2, '/user/admin', 'admin', NULL, 0); 20 | COMMIT; 21 | 22 | -- ---------------------------- 23 | -- Table structure for role 24 | -- ---------------------------- 25 | DROP TABLE IF EXISTS `role`; 26 | CREATE TABLE `role` ( 27 | `id` bigint(11) NOT NULL AUTO_INCREMENT, 28 | `name` varchar(255) NOT NULL, 29 | PRIMARY KEY (`id`) 30 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 31 | 32 | -- ---------------------------- 33 | -- Records of role 34 | -- ---------------------------- 35 | BEGIN; 36 | INSERT INTO `role` VALUES (1, 'USER'); 37 | INSERT INTO `role` VALUES (2, 'ADMIN'); 38 | COMMIT; 39 | 40 | -- ---------------------------- 41 | -- Table structure for role_permission 42 | -- ---------------------------- 43 | DROP TABLE IF EXISTS `role_permission`; 44 | CREATE TABLE `role_permission` ( 45 | `id` int(11) NOT NULL AUTO_INCREMENT, 46 | `role_id` bigint(11) NOT NULL, 47 | `permission_id` bigint(11) NOT NULL, 48 | PRIMARY KEY (`id`) 49 | ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; 50 | 51 | -- ---------------------------- 52 | -- Records of role_permission 53 | -- ---------------------------- 54 | BEGIN; 55 | INSERT INTO `role_permission` VALUES (1, 1, 1); 56 | INSERT INTO `role_permission` VALUES (2, 2, 1); 57 | INSERT INTO `role_permission` VALUES (3, 2, 2); 58 | COMMIT; 59 | 60 | -- ---------------------------- 61 | -- Table structure for user 62 | -- ---------------------------- 63 | DROP TABLE IF EXISTS `user`; 64 | CREATE TABLE `user` ( 65 | `id` bigint(11) NOT NULL AUTO_INCREMENT, 66 | `username` varchar(255) NOT NULL, 67 | `password` varchar(255) NOT NULL, 68 | PRIMARY KEY (`id`) 69 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 70 | 71 | -- ---------------------------- 72 | -- Records of user 73 | -- ---------------------------- 74 | BEGIN; 75 | INSERT INTO `user` VALUES (1, 'user', '53b432e61314e00bcc99287af9537dc4'); 76 | INSERT INTO `user` VALUES (2, 'admin', '53b432e61314e00bcc99287af9537dc4'); 77 | COMMIT; 78 | 79 | -- ---------------------------- 80 | -- Table structure for user_role 81 | -- ---------------------------- 82 | DROP TABLE IF EXISTS `user_role`; 83 | CREATE TABLE `user_role` ( 84 | `id` int(11) NOT NULL AUTO_INCREMENT, 85 | `user_id` bigint(11) NOT NULL, 86 | `role_id` bigint(11) NOT NULL, 87 | PRIMARY KEY (`id`) 88 | ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; 89 | 90 | -- ---------------------------- 91 | -- Records of user_role 92 | -- ---------------------------- 93 | BEGIN; 94 | INSERT INTO `user_role` VALUES (1, 1, 1); 95 | INSERT INTO `user_role` VALUES (3, 2, 2); 96 | COMMIT; 97 | -------------------------------------------------------------------------------- /spring_OAthu2/resource_server/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /spring_OAthu2/resource_server/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/spring_OAthu2/resource_server/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring_OAthu2/resource_server/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.5/apache-maven-3.8.5-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 3 | -------------------------------------------------------------------------------- /spring_OAthu2/resource_server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.0 9 | 10 | 11 | com.wj 12 | resource_server 13 | 0.0.1-SNAPSHOT 14 | resource_server 15 | resource Server 16 | 17 | 1.8 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-web 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-security 32 | 33 | 34 | 35 | org.springframework.security.oauth 36 | spring-security-oauth2 37 | 2.5.2.RELEASE 38 | 39 | 40 | 41 | org.projectlombok 42 | lombok 43 | true 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-test 48 | test 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-maven-plugin 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /spring_OAthu2/resource_server/src/main/java/com/wj/resource_server/ResourceServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.wj.resource_server; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ResourceServerApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ResourceServerApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /spring_OAthu2/resource_server/src/main/java/com/wj/resource_server/config/ResourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.wj.resource_server.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.annotation.Primary; 7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 8 | import org.springframework.security.config.http.SessionCreationPolicy; 9 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 12 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 13 | import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; 14 | import org.springframework.security.oauth2.provider.token.RemoteTokenServices; 15 | 16 | @Configuration 17 | @EnableResourceServer 18 | public class ResourceConfig extends ResourceServerConfigurerAdapter { 19 | 20 | @Value("${wj.appid}") 21 | private String wjAppId; 22 | 23 | @Value("${wj.appsecret}") 24 | private String wjAppSecret; 25 | 26 | /** 27 | * 密码解密类 28 | * @return 29 | */ 30 | @Bean 31 | public PasswordEncoder passwordEncoder(){ 32 | return new BCryptPasswordEncoder(); 33 | } 34 | 35 | /** 36 | * 校验 token 的正确性 37 | * @return 38 | */ 39 | @Bean 40 | @Primary 41 | public RemoteTokenServices remoteTokenServices(){ 42 | 43 | final RemoteTokenServices remoteTokenServices = new RemoteTokenServices(); 44 | remoteTokenServices.setClientId(wjAppId); 45 | remoteTokenServices.setClientSecret(wjAppSecret); 46 | remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:8082/oauth/check_token"); 47 | return remoteTokenServices; 48 | 49 | } 50 | 51 | /** 52 | * 定义资源id,以及无状态声明 53 | * @param resources 54 | */ 55 | @Override 56 | public void configure(ResourceServerSecurityConfigurer resources) { 57 | resources.resourceId("wj_resource").stateless(true); 58 | } 59 | 60 | /** 61 | * 设置 所有请求必须先授权之后再进行请求 62 | * @param http 63 | * @throws Exception 64 | */ 65 | @Override 66 | public void configure(HttpSecurity http) throws Exception { 67 | //设置创建session策略 68 | http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED); 69 | //@formatter:off 70 | //所有请求必须授权 71 | http.authorizeRequests() 72 | .anyRequest().authenticated(); 73 | //@formatter:on 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /spring_OAthu2/resource_server/src/main/java/com/wj/resource_server/controller/ResourceController.java: -------------------------------------------------------------------------------- 1 | package com.wj.resource_server.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | @RequestMapping("/rs") 9 | public class ResourceController { 10 | @GetMapping("/get_resource") 11 | public String hello() { 12 | return "我是被保护的资源接口"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring_OAthu2/resource_server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | wj: 2 | appid: user-client 3 | appsecret: 123456 4 | server: 5 | port: 8085 6 | -------------------------------------------------------------------------------- /spring_OAthu2/resource_server/src/test/java/com/wj/resource_server/ResourceServerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.wj.resource_server; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class ResourceServerApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/spring_OAthu2/springSecurityOathu2/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.5/apache-maven-3.8.5-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 3 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.0 9 | 10 | 11 | com.wj 12 | springSecurityOathu2 13 | 0.0.1-SNAPSHOT 14 | springSecurityOathu2 15 | springSecurityOathu2 Spring Boot 16 | 17 | 1.8 18 | Finchley.RELEASE 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-security 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | org.springframework.security.oauth 33 | spring-security-oauth2 34 | 2.5.2.RELEASE 35 | 36 | 37 | 38 | org.projectlombok 39 | lombok 40 | true 41 | 42 | 43 | 44 | 45 | mysql 46 | mysql-connector-java 47 | 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-jdbc 52 | 53 | 54 | com.zaxxer 55 | HikariCP 56 | 57 | 58 | 59 | 60 | 61 | com.alibaba 62 | druid-spring-boot-starter 63 | 1.2.9 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | org.springframework.boot 73 | spring-boot-devtools 74 | 75 | 76 | tk.mybatis 77 | mapper-spring-boot-starter 78 | 2.1.5 79 | 80 | 81 | 82 | 83 | 84 | 85 | org.springframework.boot 86 | spring-boot-maven-plugin 87 | 88 | 89 | 90 | org.projectlombok 91 | lombok 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/SpringsecurityOathu2Application.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurityOathu2; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | @MapperScan("com.wj.springSecurityOathu2.reposity") 9 | public class SpringsecurityOathu2Application { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringsecurityOathu2Application.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/config/AuthorityConfig.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurityOathu2.config; 2 | 3 | import org.springframework.security.crypto.password.PasswordEncoder; 4 | import org.springframework.security.oauth2.config.annotation.builders.JdbcClientDetailsServiceBuilder; 5 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 7 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 8 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 9 | import org.springframework.stereotype.Component; 10 | 11 | import javax.annotation.Resource; 12 | import javax.sql.DataSource; 13 | 14 | /** 15 | * 认证授权的 server 端 16 | */ 17 | @Component 18 | @EnableAuthorizationServer 19 | public class AuthorityConfig extends AuthorizationServerConfigurerAdapter { 20 | 21 | @Resource 22 | private PasswordEncoder passwordEncoder; 23 | 24 | @Resource 25 | private DataSource dataSource; 26 | 27 | /** 28 | * 允许表单模式的认证 29 | * @param security 30 | * @throws Exception 31 | */ 32 | @Override 33 | public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { 34 | security.allowFormAuthenticationForClients() 35 | .checkTokenAccess("permitAll()"); 36 | } 37 | 38 | /** 39 | * 配置所有客户端的信息(client_id、secret、授权模式、scope、资源id 以及重定向地址) 40 | * @param clients 41 | * @throws Exception 42 | */ 43 | @Override 44 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 45 | /** 46 | * 方法一:内存配置 47 | */ 48 | // clients.inMemory() 49 | // .withClient("user-client") 50 | // .secret(passwordEncoder.encode("123456")) 51 | // .authorizedGrantTypes("authorization_code") 52 | // .scopes("all") 53 | // .resourceIds("wj_resource") 54 | // .redirectUris("http://localhost:8082/user/hello"); 55 | 56 | /** 57 | * 方法二:db配置 58 | */ 59 | JdbcClientDetailsServiceBuilder jcsb = clients.jdbc(dataSource); 60 | jcsb.passwordEncoder(passwordEncoder); 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | //package com.wj.springSecurityOathu2.config; 2 | // 3 | //import com.wj.springSecurityOathu2.entity.Permission; 4 | //import com.wj.springSecurityOathu2.reposity.PermissionMapper; 5 | //import lombok.extern.slf4j.Slf4j; 6 | //import org.springframework.context.annotation.Bean; 7 | //import org.springframework.context.annotation.Configuration; 8 | //import org.springframework.security.config.annotation.web.builders.HttpSecurity; 9 | //import org.springframework.security.config.annotation.web.builders.WebSecurity; 10 | //import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; 11 | //import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; 12 | //import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 13 | //import org.springframework.security.crypto.password.PasswordEncoder; 14 | //import org.springframework.security.web.SecurityFilterChain; 15 | // 16 | //import javax.annotation.Resource; 17 | //import java.util.List; 18 | // 19 | //@Configuration 20 | //@Slf4j 21 | //public class SecurityConfig { 22 | // 23 | // @Resource 24 | // private PermissionMapper permissionMapper; 25 | // 26 | // @Bean 27 | // public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 28 | // ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry 29 | // authorizeRequests = http.csrf().disable().authorizeRequests(); 30 | //// 方式二:配置来源于数据库 31 | //// 1.查询到所有的权限 32 | // List allPermission = permissionMapper.findAllPermission(); 33 | //// 2.分别添加权限规则 34 | // allPermission.forEach((p -> { 35 | // authorizeRequests.antMatchers(p.getUrl()).hasAnyAuthority(p.getName()) ; 36 | // })); 37 | // 38 | // authorizeRequests.antMatchers("/**").fullyAuthenticated() 39 | // .anyRequest().authenticated().and().formLogin(); 40 | // return http.build(); 41 | // } 42 | // 43 | // @Bean 44 | // WebSecurityCustomizer webSecurityCustomizer() { 45 | // return new WebSecurityCustomizer() { 46 | // @Override 47 | // public void customize(WebSecurity web) { 48 | // web.ignoring().antMatchers("/hello"); 49 | // web.ignoring().antMatchers("/css/**", "/js/**"); 50 | // } 51 | // }; 52 | // } 53 | // 54 | // @Bean 55 | // public PasswordEncoder passwordEncoder(){ 56 | // return new BCryptPasswordEncoder(); 57 | // } 58 | // 59 | //} 60 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurityOathu2.config; 2 | 3 | import com.wj.springSecurityOathu2.entity.User; 4 | import com.wj.springSecurityOathu2.reposity.PermissionMapper; 5 | import com.wj.springSecurityOathu2.service.UserService; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 12 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 13 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 14 | import org.springframework.security.crypto.password.PasswordEncoder; 15 | import javax.annotation.Resource; 16 | 17 | @Configuration 18 | @EnableWebSecurity 19 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 20 | @Resource 21 | private UserService userService; 22 | 23 | @Resource 24 | private PermissionMapper permissionMapper; 25 | 26 | /** 27 | * 将用户配置在内存或者mysql中(可登录用户,包括用户名、密码和角色) 28 | * @param auth 29 | * @throws Exception 30 | */ 31 | @Override 32 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 33 | // 方式一:写到内存 34 | auth.inMemoryAuthentication() 35 | .withUser("admin").password(passwordEncoder().encode("123456")).authorities("admin") 36 | .and() 37 | .withUser("user").password(passwordEncoder().encode("123456")).authorities("common"); 38 | // 方式二:来源于数据库 39 | auth.userDetailsService(userService).passwordEncoder(passwordEncoder()); 40 | 41 | // System.out.println("密码:"+new BCryptPasswordEncoder().encode("123456")); 42 | } 43 | 44 | /** 45 | * 登录处理-配置对应用户所拥有的权限(url、authority对应的所有关系) 46 | * @param http 47 | * @throws Exception 48 | */ 49 | @Override 50 | protected void configure(HttpSecurity http) throws Exception { 51 | 52 | // 方式一:写死的方式 53 | http.authorizeRequests(). 54 | antMatchers("/user/common").hasAnyAuthority("admin") 55 | .antMatchers("/user/admin").hasAnyAuthority("admin") 56 | .antMatchers("/user/common").hasAnyAuthority("common") 57 | .antMatchers("/**").fullyAuthenticated() 58 | .anyRequest().authenticated() 59 | .and().formLogin(); 60 | 61 | // 方式二:配置来源于数据库 62 | // ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry 63 | // authorizeRequests = http.csrf().disable().authorizeRequests(); 64 | // 1.查询到所有的权限 65 | // List allPermission = permissionMapper.findAllPermission(); 66 | // 2.分别添加权限规则 67 | // allPermission.forEach((p -> { 68 | // authorizeRequests.antMatchers(p.getUrl()).hasAnyAuthority(p.getName()) ; 69 | // })); 70 | // 71 | // authorizeRequests.antMatchers("/**").fullyAuthenticated() 72 | // .anyRequest().authenticated().and().formLogin(); 73 | 74 | 75 | } 76 | 77 | /** 78 | * 忽略拦截处理 79 | * @param web 80 | * @throws Exception 81 | */ 82 | @Override 83 | public void configure(WebSecurity web) throws Exception { 84 | // 设置拦截忽略url - 会直接过滤该url - 将不会经过Spring Security过滤器链 85 | web.ignoring().antMatchers("/getUserInfo"); 86 | // 设置拦截忽略文件夹,可以对静态资源放行 87 | web.ignoring().antMatchers("/css/**", "/js/**"); 88 | } 89 | 90 | /** 91 | * 密码解密类 92 | * @return 93 | */ 94 | @Bean 95 | public PasswordEncoder passwordEncoder(){ 96 | return new BCryptPasswordEncoder(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurityOathu2.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RequestParam; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController 9 | @RequestMapping("/user") 10 | public class UserController { 11 | 12 | @GetMapping("/common") 13 | public String common() { 14 | return "hello~ common"; 15 | } 16 | 17 | @GetMapping("/admin") 18 | public String admin() { 19 | return "hello~ admin"; 20 | } 21 | 22 | @GetMapping("/hello") 23 | public String hello(@RequestParam("code") String code) { 24 | return "hello~ 授权码 code 为:" + code; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/entity/Permission.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurityOathu2.entity; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Permission { 7 | private Integer id; 8 | 9 | private String url; 10 | 11 | private String name; 12 | 13 | private String description; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/entity/Role.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurityOathu2.entity; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Role { 7 | private Integer id; 8 | private String name; 9 | } 10 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurityOathu2.entity; 2 | 3 | import lombok.Data; 4 | import org.springframework.security.core.GrantedAuthority; 5 | import org.springframework.security.core.userdetails.UserDetails; 6 | 7 | import java.util.ArrayList; 8 | import java.util.Collection; 9 | import java.util.List; 10 | 11 | @Data 12 | public class User implements UserDetails { 13 | private Integer id; 14 | private String username; 15 | private String password; 16 | private String role; 17 | 18 | // 用户所有权限 19 | private List authorities = new ArrayList(); 20 | 21 | public Collection getAuthorities() { 22 | 23 | return authorities; 24 | } 25 | 26 | @Override 27 | public boolean isAccountNonExpired() { 28 | return true; 29 | } 30 | 31 | @Override 32 | public boolean isAccountNonLocked() { 33 | return true; 34 | } 35 | 36 | @Override 37 | public boolean isCredentialsNonExpired() { 38 | return true; 39 | } 40 | 41 | @Override 42 | public boolean isEnabled() { 43 | return true; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/reposity/PermissionMapper.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurityOathu2.reposity; 2 | 3 | import com.wj.springSecurityOathu2.entity.Permission; 4 | import org.apache.ibatis.annotations.Select; 5 | 6 | import java.util.List; 7 | 8 | public interface PermissionMapper { 9 | 10 | 11 | /** 12 | * 查询用户的权限根据用户查询权限 13 | * 14 | * @return 15 | */ 16 | @Select("select * from permission") 17 | List findAllPermission(); 18 | } 19 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/reposity/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurityOathu2.reposity; 2 | 3 | import com.wj.springSecurityOathu2.entity.Permission; 4 | import com.wj.springSecurityOathu2.entity.User; 5 | import org.apache.ibatis.annotations.Param; 6 | import org.apache.ibatis.annotations.Select; 7 | 8 | import java.util.List; 9 | 10 | public interface UserMapper { 11 | 12 | /** 13 | * 根据用户名称查询 14 | * 15 | * @param userName 16 | * @return 17 | */ 18 | @Select(" select * from user where username = #{userName}") 19 | User findByUsername(@Param("userName") String userName); 20 | 21 | /** 22 | * 查询用户的权限根据用户查询权限 23 | * 24 | * @param userName 25 | * @return 26 | */ 27 | @Select(" SELECT d.*\n" + 28 | "from user a,user_role b,role_permission c,permission d\n" + 29 | "WHERE \n" + 30 | "a.id = b.user_id\n" + 31 | "and b.role_id = c.role_id\n" + 32 | "and c.permission_id = d.id\n" + 33 | "and \n" + 34 | "a.username= #{userName};") 35 | List findPermissionByUsername(@Param("userName") String userName); 36 | } 37 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurityOathu2.service; 2 | 3 | import com.wj.springSecurityOathu2.entity.User; 4 | import org.springframework.security.core.userdetails.UserDetailsService; 5 | 6 | public interface UserService extends UserDetailsService { 7 | 8 | 9 | } -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/java/com/wj/springSecurityOathu2/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.wj.springSecurityOathu2.service; 2 | 3 | import com.wj.springSecurityOathu2.entity.Permission; 4 | import com.wj.springSecurityOathu2.entity.User; 5 | import com.wj.springSecurityOathu2.reposity.UserMapper; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.security.core.GrantedAuthority; 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 11 | import org.springframework.stereotype.Service; 12 | 13 | import javax.annotation.Resource; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | @Slf4j 18 | @Service 19 | public class UserServiceImpl implements UserService { 20 | 21 | @Resource 22 | private UserMapper userMapper; 23 | 24 | @Override 25 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 26 | // 1.根据用户名称查询到user用户
 27 | User userDetails = userMapper.findByUsername(username); 28 | if (userDetails == null) { 29 | return null; 30 | } 31 | // 2.查询该用户对应的权限
 32 | List permissionList = userMapper.findPermissionByUsername(username); 33 | List grantedAuthorities = new ArrayList<>(); 34 | permissionList.forEach((a) -> grantedAuthorities.add(new SimpleGrantedAuthority(a.getName()))); 35 | log.info(">>permissionList:{}<<", permissionList); 36 | // 设置权限
 37 | userDetails.setAuthorities(grantedAuthorities); 38 | return userDetails; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8082 3 | 4 | spring: 5 | datasource: 6 | url: jdbc:mysql://localhost:3306/security_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false 7 | username: root 8 | password: 123456 9 | # driver-class-name: com.mysql.jdbc.Driver 10 | # druid: 11 | # initialSize: 1 12 | # minIdle: 1 13 | # maxActive: 50 14 | # maxWait: 6000 15 | # timeBetweenEvictionRunsMillis: 6000 16 | # minEvictableIdleTimeMillis: 30000 17 | # testWhileIdle: true 18 | # testOnBorrow: true 19 | # testOnReturn: true 20 | # validationQuery: SELECT 1 from dual 21 | # connectionProperties: config.decrypt=false -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/main/resources/oauth_client_details.sql: -------------------------------------------------------------------------------- 1 | create table oauth_client_details ( client_id VARCHAR(256) PRIMARY KEY, resource_ids VARCHAR(256), client_secret VARCHAR(256), scope VARCHAR(256), authorized_grant_types VARCHAR(256), web_server_redirect_uri VARCHAR(256), authorities VARCHAR(256), access_token_validity INTEGER, refresh_token_validity INTEGER, additional_information VARCHAR(4096), autoapprove VARCHAR(256)); 2 | INSERT INTO `security_demo`.`oauth_client_details`(`client_id`, `resource_ids`, `client_secret`, `scope`, `authorized_grant_types`, `web_server_redirect_uri`, `authorities`, `access_token_validity`, `refresh_token_validity`, `additional_information`, `autoapprove`) VALUES ('order-client', NULL, '$2a$10$4zd/aj2BNJhuM5PIs5BupO8tiN2yikzP7JMzNaq1fXhcXUefWCOF2', 'all', 'authorization_code,refresh_token,password', 'http://localhost:8082/user/hello', NULL, 3600, 36000, NULL, '1'); 3 | INSERT INTO `security_demo`.`oauth_client_details`(`client_id`, `resource_ids`, `client_secret`, `scope`, `authorized_grant_types`, `web_server_redirect_uri`, `authorities`, `access_token_validity`, `refresh_token_validity`, `additional_information`, `autoapprove`) VALUES ('user-client', NULL, '$2a$10$4zd/aj2BNJhuM5PIs5BupO8tiN2yikzP7JMzNaq1fXhcXUefWCOF2', 'all', 'authorization_code,refresh_token,password', 'http://localhost:8082/user/hello', NULL, 3600, 36000, NULL, '1'); 4 | -------------------------------------------------------------------------------- /spring_OAthu2/springSecurityOathu2/src/test/java/com/wj/springSecurityOathu2/SpringsecurityOathu2ApplicationTests.java: -------------------------------------------------------------------------------- 1 | //package com.wj.springSecurityOathu2; 2 | // 3 | //import org.junit.jupiter.api.Test; 4 | //import org.springframework.boot.test.context.SpringBootTest; 5 | // 6 | //@SpringBootTest 7 | //class springSecurityOathu2Oathu2ApplicationTests { 8 | // 9 | // @Test 10 | // void contextLoads() { 11 | // } 12 | // 13 | //} 14 | -------------------------------------------------------------------------------- /spring_jdbc/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /spring_jdbc/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helemile/Spring-Boot-Notes/2dd50bbeeaaa4949f53933164f248d03e42c528d/spring_jdbc/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring_jdbc/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /spring_jdbc/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.2.5.RELEASE 9 | 10 | 11 | com.shumile 12 | spring_jdbc 13 | 0.0.1-SNAPSHOT 14 | spring_jdbc 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-jdbc 26 | 27 | 28 | 29 | 30 | mysql 31 | mysql-connector-java 32 | 33 | 34 | 35 | 36 | 37 | org.projectlombok 38 | lombok 39 | true 40 | 41 | 42 | 43 | 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-maven-plugin 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /spring_jdbc/src/main/java/com/shumile/spring_jdbc/SpringJdbcApplication.java: -------------------------------------------------------------------------------- 1 | package com.shumile.spring_jdbc; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.ApplicationArguments; 5 | import org.springframework.boot.ApplicationRunner; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | 9 | @SpringBootApplication 10 | 11 | public class SpringJdbcApplication implements ApplicationRunner { 12 | 13 | @Autowired 14 | private UserDao userDao; 15 | 16 | public static void main(String[] args) { 17 | SpringApplication.run(SpringJdbcApplication.class, args); 18 | } 19 | 20 | @Override 21 | public void run(ApplicationArguments args) throws Exception { 22 | userDao.addUser(); 23 | userDao.listData(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /spring_jdbc/src/main/java/com/shumile/spring_jdbc/User.java: -------------------------------------------------------------------------------- 1 | package com.shumile.spring_jdbc; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Data 7 | @Builder 8 | public class User { 9 | private long id; 10 | 11 | private String name; 12 | 13 | private int age; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /spring_jdbc/src/main/java/com/shumile/spring_jdbc/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.shumile.spring_jdbc; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.jdbc.core.JdbcTemplate; 6 | import org.springframework.jdbc.core.RowMapper; 7 | import org.springframework.stereotype.Repository; 8 | import java.sql.ResultSet; 9 | import java.sql.SQLException; 10 | import java.util.List; 11 | 12 | @Slf4j 13 | @Repository 14 | public class UserDao { 15 | @Autowired 16 | private JdbcTemplate jdbcTemplate; 17 | /** 18 | * 添加用户 19 | */ 20 | public void addUser() { 21 | User user = User.builder(). 22 | id(1L).name("舒米君").age(18).build(); 23 | jdbcTemplate.update 24 | ("insert t_user values(?,?,?)", 25 | new Object[]{user.getId(), user.getName(), user.getAge()} 26 | ); 27 | log.info("user :{} added",user); 28 | } 29 | /** 30 | * 获取总数 31 | * 32 | * @return 33 | */ 34 | private Long getCount() { 35 | 36 | return jdbcTemplate 37 | .queryForObject("select count(1) from t_user", Long.class); 38 | } 39 | 40 | /** 41 | * 采用RowMapper的方式,获取结果对象。 42 | */ 43 | public void listData() { 44 | log.info("Count:{}", getCount()); 45 | //采用RowMapper的方式,获取结果对象。 46 | List userList2 = jdbcTemplate.query("select * from t_user", new RowMapper() { 47 | @Override 48 | public User mapRow(ResultSet resultSet, int i) throws SQLException { 49 | return User.builder() 50 | .id(resultSet.getLong(1) 51 | ).name(resultSet.getString("name") 52 | ).age(resultSet.getInt("age")) 53 | .build(); 54 | } 55 | }); 56 | userList2.forEach(user -> log.info("User2:{}", user)); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /spring_jdbc/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8 2 | spring.datasource.username=root 3 | spring.datasource.password=123456 4 | #可以不用配置数据库驱动,SpringBoot 会根据引入的依赖进行自动配置 5 | #spring.datasource.driver-class-name=com.mysql.jdbc.Driver 6 | -------------------------------------------------------------------------------- /spring_jdbc/src/test/java/com/shumile/spring_jdbc/SpringJdbcApplicationTests.java: -------------------------------------------------------------------------------- 1 | //package com.shumile.spring_jdbc; 2 | // 3 | //import org.junit.jupiter.api.Test; 4 | //import org.springframework.boot.test.context.SpringBootTest; 5 | // 6 | //@SpringBootTest 7 | //class SpringJdbcApplicationTests { 8 | // 9 | // @Test 10 | // void contextLoads() { 11 | // } 12 | // 13 | //} 14 | --------------------------------------------------------------------------------