├── .drone.yml ├── .gitignore ├── Dockerfile ├── License ├── README.md ├── User.sql ├── images └── QQ截图20190105230741.png └── security ├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── logs ├── error │ ├── online-study.2019-01-05.error │ ├── online-study.2019-01-07.error │ └── online-study.2019-01-09.error └── log │ ├── online-study.2019-01-04.log │ ├── online-study.2019-01-05.log │ ├── online-study.2019-01-07.log │ └── online-study.2019-01-09.log ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ └── security │ │ ├── Exception │ │ └── RewriteAccessDenyFilter.java │ │ ├── SecurityApplication.java │ │ ├── config │ │ ├── CrossFilter.java │ │ ├── DruidDataSourceConfigurer.java │ │ ├── DruidMonitorConfigurer.java │ │ ├── RedisConfigurer.java │ │ └── WebSecurity.java │ │ ├── controller │ │ ├── AuthController.java │ │ ├── PermissionController.java │ │ ├── RoleController.java │ │ └── UserController.java │ │ ├── entity │ │ ├── Permission.java │ │ ├── Role.java │ │ ├── RolePermission.java │ │ └── User.java │ │ ├── jwt │ │ ├── JwtAuthenticationTokenFilter.java │ │ ├── JwtTokenUtil.java │ │ └── JwtUser.java │ │ ├── mapper │ │ ├── PermissionMapper.java │ │ ├── RoleMapper.java │ │ └── UserMapper.java │ │ ├── service │ │ ├── PermissionService.java │ │ ├── RoleService.java │ │ ├── UserService.java │ │ └── impl │ │ │ ├── JwtUserDetailsServiceImpl.java │ │ │ ├── PermissionServiceImpl.java │ │ │ ├── RoleServiceImpl.java │ │ │ └── UserServiceImpl.java │ │ └── util │ │ ├── AesEncryptUtil.java │ │ ├── BulidTree.java │ │ ├── GenTree.java │ │ ├── Menu.java │ │ ├── MenuMetaVo.java │ │ ├── PageUtil.java │ │ ├── RedisUtil.java │ │ ├── RetCode.java │ │ ├── RetResult.java │ │ ├── SnowFlake.java │ │ └── UserVo.java └── resources │ ├── application-dev.yml │ ├── application.yml │ ├── logback.xml │ └── mapper │ └── user │ ├── PermissionMapper.xml │ ├── RoleMapper.xml │ └── UserMapper.xml └── test └── java └── com └── example └── security └── SecurityApplicationTests.java /.drone.yml: -------------------------------------------------------------------------------- 1 | kind: pipeline 2 | name: Spring_Vue_Template 3 | 4 | 5 | # 通过配置Maven 打包Jar文件 6 | steps: 7 | - name: Maven compile 8 | image: maven 9 | pull: if-not-exists 10 | volumes: 11 | - name: cache 12 | path: /root/.m2 13 | commands: 14 | - mvn clean package -Dmaven.test.skip=true 15 | 16 | # 获取得到上面Maven构建成功的Jar包然后根据.Dockerfile来构建Docker镜像(我这里是推送到了私人镜像仓库中) 17 | - name: Docker build 18 | image: docker:latest 19 | pull: if-not-exists 20 | volumes: 21 | - name: docker 22 | path: /var/run/docker.sock 23 | commands: 24 | - docker version 25 | - docker login -u *** --password *** ***.*** 26 | - time docker build -f Dockerfile -t ***/***:latest . 27 | - time docker push ***/***:latest 28 | - docker system prune -f 29 | 30 | # 这里使用了一个SSH工具重新运行新镜像 31 | - name: Ssh commands 32 | image: appleboy/drone-ssh 33 | pull: if-not-exists 34 | settings: 35 | host: *** 36 | username: username 37 | repo: ${org_secret} 38 | password: 39 | from_secret: ${secret_name} 40 | port: 22 41 | script: 42 | - echo ====暂停容器开始======= 43 | - docker stop `docker ps -a| grep ${镜像名} | awk '{print $1}' ` 44 | - docker rm -f `docker ps -a| grep ${镜像名} | awk '{print $1}' ` 45 | - docker rmi $(docker images | grep "none" | awk '{print $3}') 46 | - echo ====开始部署======= 47 | - docker run -detach --publish 8086:8086 --name=${镜像名} --restart=always ${仓库地址}:latest 48 | - echo ====部署成功====== 49 | 50 | # 发送构建结果到钉钉上(可选) 51 | - name: DingTalk notification 52 | image: guoxudongdocker/drone-dingtalk 53 | pull: if-not-exists 54 | settings: 55 | repo: ${org_secret} 56 | token: 57 | from_secret: ${secret_name} 58 | type: markdown 59 | message_color: true 60 | message_pic: true 61 | sha_link: true 62 | when: 63 | status: [failure, success] 64 | 65 | # 缓存 66 | volumes: 67 | - name: cache 68 | host: 69 | # path: /tmp/cache/.m2 70 | path: /var/lib/cache # The path be used in the host. 71 | - name: docker 72 | host: 73 | path: /var/run/docker.sock 74 | # 当master分支有代码提交时,回触发Drone工作 75 | trigger: 76 | branch: 77 | - master -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | 27 | ### log ### 28 | logs/ 29 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:8u181-jdk-alpine 2 | VOLUME /tmp 3 | ENV TZ=Asia/Shanghai 4 | RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone 5 | COPY ./target/security-0.0.1-SNAPSHOT.jar security-java.jar 6 | EXPOSE 8086 7 | ENTRYPOINT ["java","-jar","-Xms128m","-Xmx256m","/security-java.jar"] 8 | -------------------------------------------------------------------------------- /License: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # springSecurity-jwt-vue-temple Demo 2 | # 如果对你有帮助,希望可以点个Star支持一下~ 3 | ## 简介 4 | [springSecurity-jwt-vue-temple](https://github.com/ywbjja/springSecurity-jwt-vue-temple)是一个基于Spring Boot+Vue的后台管理系统模板,使用了[Vue_templete](https://github.com/ywbjja/Vue_templete)为前端框架,项目目前实现了基于Spring Security 的安全解决方案,实现了动态路由,权限验证,以及一些基本功能。可以帮您快速搭建一个企业级的后台管理解决方案,目前正在开发阶段,如果您有哪怕一个小小的建议欢迎联系我,可以在`issues`或者通过微信公众号、知乎联系我。 5 | ### 个人微信公众号 6 | ![个人微信公众号](https://i.imgur.com/9cdsEWT.jpg) 7 | 8 | ### 知乎 9 | ![知乎](https://i.imgur.com/2RtBYZm.png) 10 | 11 | ### 系列教程已经更新到知乎上 12 | 13 | - [Spring Security(一):整合JWT实现登录功能](https://zhuanlan.zhihu.com/p/54844487) 14 | - [Spring Security(二):获取用户权限菜单树](https://zhuanlan.zhihu.com/p/54845240) 15 | - [Spring Security(三):与Vue.js整合](https://zhuanlan.zhihu.com/p/54845426) 16 | - [Spring Security(四):更新前端路由获取方式](https://zhuanlan.zhihu.com/p/55203657) 17 | - [Spring Security(五):前后端权限控制详解](https://zhuanlan.zhihu.com/p/55392971) 18 | - [Spring Security(六):前端菜单,角色权限页面的搭建](https://zhuanlan.zhihu.com/p/55823589) 19 | - [Spring Security(七):自定义拦截器实现对权限异常的处理](https://zhuanlan.zhihu.com/p/55900345) 20 | - [Spring Security(八):Vue.js使用 CryptoJS加密密码以及BCryptPasswordEncoder的使用](https://zhuanlan.zhihu.com/p/56252316) 21 | - [Spring Security(九):JWT过期刷新问题,实现十五天免登陆](https://zhuanlan.zhihu.com/p/57608281) 22 | 23 | ### 持续集成 24 | - [Drone + Docker + Gogs实现持续集成](https://zhuanlan.zhihu.com/p/108842332) 25 | 26 | # Getting started 27 | 28 | ``` 29 | 30 | # clone the project 31 | 32 | vue: 33 | git clone https://github.com/ywbjja/Vue_templete.git 34 | 35 | Spring: 36 | https://github.com/ywbjja/springSecurity-jwt-vue-temple.git 37 | 38 | # install dependency 39 | npm install 40 | 41 | # develop 42 | npm run dev 43 | 44 | ``` 45 | -------------------------------------------------------------------------------- /User.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Date: 06/01/2019 13:43:01 4 | */ 5 | 6 | SET NAMES utf8mb4; 7 | 8 | 9 | -- ---------------------------- 10 | -- Table structure for User 11 | -- ---------------------------- 12 | DROP TABLE IF EXISTS `User`; 13 | CREATE TABLE `User` ( 14 | `id` bigint(20) NOT NULL, 15 | `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 16 | `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 17 | PRIMARY KEY (`id`) USING BTREE 18 | ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; 19 | 20 | -- ---------------------------- 21 | -- Records of User 22 | -- ---------------------------- 23 | INSERT INTO `User` VALUES (1, 'admin', '$2a$10$rIX9ewyHU2ROytz1ryWEi.YLEtxIhgcQi8WR/7YAcKBl/rZ/4m0jC'); 24 | INSERT INTO `User` VALUES (2, '123456', '$2a$10$rIX9ewyHU2ROytz1ryWEi.YLEtxIhgcQi8WR/7YAcKBl/rZ/4m0jC'); 25 | INSERT INTO `User` VALUES (221, 'test021', '$2a$10$D6iS9ohqNq338TqMRe8AN.ojrjDHDYIjgLSlUQkfacWrml6VZjuTK'); 26 | INSERT INTO `User` VALUES (222, 'test01', '$2a$10$1.4hJD5uefd/u5ARik0xE.pKsgaufAHS4gfLFvMHPkCPMr7hzduFG'); 27 | 28 | 29 | 30 | -- ---------------------------- 31 | -- Table structure for RoleUser 32 | -- ---------------------------- 33 | DROP TABLE IF EXISTS `RoleUser`; 34 | CREATE TABLE `RoleUser` ( 35 | `id` bigint(20) NOT NULL, 36 | `userId` bigint(20) NULL DEFAULT NULL, 37 | `roleId` bigint(20) NULL DEFAULT NULL, 38 | PRIMARY KEY (`id`) USING BTREE 39 | ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; 40 | 41 | -- ---------------------------- 42 | -- Records of RoleUser 43 | -- ---------------------------- 44 | INSERT INTO `RoleUser` VALUES (1, 1, 1); 45 | INSERT INTO `RoleUser` VALUES (2, 2, 2); 46 | 47 | 48 | 49 | SET FOREIGN_KEY_CHECKS=0; 50 | 51 | -- ---------------------------- 52 | -- Table structure for Role 53 | -- ---------------------------- 54 | DROP TABLE IF EXISTS `Role`; 55 | CREATE TABLE `Role` ( 56 | `id` bigint(20) NOT NULL, 57 | `rolename` varchar(255) DEFAULT NULL, 58 | `roledesc` varchar(100) DEFAULT NULL COMMENT '角色描述', 59 | `createTime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间', 60 | PRIMARY KEY (`id`) 61 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 62 | 63 | -- ---------------------------- 64 | -- Records of Role 65 | -- ---------------------------- 66 | INSERT INTO `Role` VALUES ('1', 'ROLE_ADMIN', '系统管理员', '2019-01-21 11:02:32'); 67 | INSERT INTO `Role` VALUES ('2', 'ROLE_USER', '用户测试001', '2019-01-21 11:02:42'); 68 | 69 | 70 | SET FOREIGN_KEY_CHECKS=0; 71 | 72 | -- ---------------------------- 73 | -- Table structure for Permission 74 | -- ---------------------------- 75 | DROP TABLE IF EXISTS `Permission`; 76 | CREATE TABLE `Permission` ( 77 | `per_id` bigint(11) NOT NULL, 78 | `per_parent_id` bigint(11) DEFAULT NULL, 79 | `per_name` varchar(100) DEFAULT NULL COMMENT '权限名称', 80 | `per_resource` varchar(100) DEFAULT NULL COMMENT '权限资源', 81 | `per_type` varchar(100) DEFAULT NULL COMMENT '权限类型', 82 | `per_icon` varchar(100) DEFAULT NULL COMMENT '图标', 83 | `per_describe` varchar(100) DEFAULT NULL COMMENT '权限描述', 84 | `per_component` varchar(255) DEFAULT NULL, 85 | `per_sort` int(11) DEFAULT NULL, 86 | `per_crtTime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间', 87 | PRIMARY KEY (`per_id`) 88 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 89 | 90 | -- ---------------------------- 91 | -- Records of Permission 92 | -- ---------------------------- 93 | INSERT INTO `Permission` VALUES ('1101', '0', '权限管理', 'auth', 'menu', 'auth', '权限管理菜单', '', '1', '2019-01-24 10:04:22'); 94 | INSERT INTO `Permission` VALUES ('1102', '1101', '角色管理', 'role', 'menu', 'role', '角色管理菜单', 'pre/role/index', '101', '2019-04-18 16:05:03'); 95 | INSERT INTO `Permission` VALUES ('1103', '1101', '资源管理', 'per', 'menu', 'resource', '资源管理菜单', 'pre/perm/index', '102', '2019-01-22 10:51:43'); 96 | INSERT INTO `Permission` VALUES ('285779921140461568', '1101', '角色权限', 'roleauth', 'menu', 'roleauth', null, 'pre/roleauth/index', '104', '2019-01-24 12:29:52'); 97 | 98 | 99 | 100 | SET FOREIGN_KEY_CHECKS=0; 101 | 102 | -- ---------------------------- 103 | -- Table structure for RolePermission 104 | -- ---------------------------- 105 | DROP TABLE IF EXISTS `RolePermission`; 106 | CREATE TABLE `RolePermission` ( 107 | `rp_id` bigint(20) NOT NULL, 108 | `rp_role_id` bigint(20) DEFAULT NULL COMMENT '角色id', 109 | `rp_per_id` bigint(20) DEFAULT NULL COMMENT '权限id', 110 | PRIMARY KEY (`rp_id`) 111 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 112 | 113 | -- ---------------------------- 114 | -- Records of RolePermission 115 | -- ---------------------------- 116 | INSERT INTO `RolePermission` VALUES ('286859857880166400', '1', '1101'); 117 | INSERT INTO `RolePermission` VALUES ('286859857980829696', '1', '1102'); 118 | INSERT INTO `RolePermission` VALUES ('286859858081492992', '1', '1103'); 119 | INSERT INTO `RolePermission` VALUES ('286859858177961984', '1', '285779921140461568'); 120 | INSERT INTO `RolePermission` VALUES ('286904710097809408', '2', '1101'); 121 | INSERT INTO `RolePermission` VALUES ('286904710232027136', '2', '1102'); 122 | INSERT INTO `RolePermission` VALUES ('286904710332690432', '2', '1103'); 123 | 124 | 125 | -------------------------------------------------------------------------------- /images/QQ截图20190105230741.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ywbjja/springSecurity-jwt-vue-temple/1e742e7bac36f4370686782ca5dd28d4ee435675/images/QQ截图20190105230741.png -------------------------------------------------------------------------------- /security/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | 27 | ### log ### 28 | logs/ 29 | -------------------------------------------------------------------------------- /security/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ywbjja/springSecurity-jwt-vue-temple/1e742e7bac36f4370686782ca5dd28d4ee435675/security/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /security/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip 2 | -------------------------------------------------------------------------------- /security/logs/error/online-study.2019-01-05.error: -------------------------------------------------------------------------------- 1 | 【xkcoding】2019-01-05 21:39:44.525 ERROR [http-nio-8089-exec-2] o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.security.service.UserService.login] with root cause 2 | org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.security.service.UserService.login 3 | at org.apache.ibatis.binding.MapperMethod$SqlCommand.(MapperMethod.java:225) 4 | at org.apache.ibatis.binding.MapperMethod.(MapperMethod.java:48) 5 | at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65) 6 | at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58) 7 | at com.sun.proxy.$Proxy68.login(Unknown Source) 8 | at com.example.security.controller.AuthController.login(AuthController.java:30) 9 | at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 10 | at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 11 | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 12 | at java.lang.reflect.Method.invoke(Method.java:498) 13 | at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) 14 | at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) 15 | at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) 16 | at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) 17 | at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) 18 | at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) 19 | at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) 20 | at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) 21 | at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) 22 | at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) 23 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) 24 | at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) 25 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) 26 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) 27 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 28 | at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) 29 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 30 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 31 | at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) 32 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 33 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 34 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 35 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) 36 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 37 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 38 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) 39 | at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) 40 | at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) 41 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 42 | at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) 43 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 44 | at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) 45 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 46 | at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) 47 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 48 | at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) 49 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 50 | at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) 51 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 52 | at com.example.security.jwt.JwtAuthenticationTokenFilter.doFilterInternal(JwtAuthenticationTokenFilter.java:55) 53 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 54 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 55 | at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) 56 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 57 | at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) 58 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 59 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 60 | at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) 61 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 62 | at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) 63 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 64 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 65 | at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) 66 | at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) 67 | at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347) 68 | at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263) 69 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 70 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 71 | at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) 72 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 73 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 74 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 75 | at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) 76 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 77 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 78 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 79 | at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) 80 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 81 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 82 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 83 | at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) 84 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 85 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 86 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 87 | at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) 88 | at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) 89 | at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) 90 | at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) 91 | at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) 92 | at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) 93 | at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) 94 | at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) 95 | at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) 96 | at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) 97 | at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) 98 | at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) 99 | at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) 100 | at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) 101 | at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) 102 | at java.lang.Thread.run(Thread.java:748) 103 | 【xkcoding】2019-01-05 21:41:10.113 ERROR [http-nio-8089-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.security.service.UserService.login] with root cause 104 | org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.security.service.UserService.login 105 | at org.apache.ibatis.binding.MapperMethod$SqlCommand.(MapperMethod.java:225) 106 | at org.apache.ibatis.binding.MapperMethod.(MapperMethod.java:48) 107 | at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65) 108 | at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58) 109 | at com.sun.proxy.$Proxy68.login(Unknown Source) 110 | at com.example.security.controller.AuthController.login(AuthController.java:30) 111 | at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 112 | at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 113 | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 114 | at java.lang.reflect.Method.invoke(Method.java:498) 115 | at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) 116 | at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) 117 | at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) 118 | at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) 119 | at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) 120 | at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) 121 | at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) 122 | at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) 123 | at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) 124 | at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) 125 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) 126 | at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) 127 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) 128 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) 129 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 130 | at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) 131 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 132 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 133 | at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) 134 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 135 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 136 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 137 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) 138 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 139 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 140 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) 141 | at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) 142 | at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) 143 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 144 | at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) 145 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 146 | at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) 147 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 148 | at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) 149 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 150 | at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) 151 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 152 | at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) 153 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 154 | at com.example.security.jwt.JwtAuthenticationTokenFilter.doFilterInternal(JwtAuthenticationTokenFilter.java:55) 155 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 156 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 157 | at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) 158 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 159 | at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) 160 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 161 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 162 | at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) 163 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 164 | at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) 165 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 166 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 167 | at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) 168 | at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) 169 | at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347) 170 | at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263) 171 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 172 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 173 | at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) 174 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 175 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 176 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 177 | at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) 178 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 179 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 180 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 181 | at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) 182 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 183 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 184 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 185 | at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) 186 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 187 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 188 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 189 | at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) 190 | at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) 191 | at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) 192 | at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) 193 | at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) 194 | at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) 195 | at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) 196 | at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) 197 | at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) 198 | at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) 199 | at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) 200 | at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) 201 | at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) 202 | at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) 203 | at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) 204 | at java.lang.Thread.run(Thread.java:748) 205 | 【xkcoding】2019-01-05 21:47:25.120 ERROR [http-nio-8089-exec-10] o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.security.service.UserService.login] with root cause 206 | org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.security.service.UserService.login 207 | at org.apache.ibatis.binding.MapperMethod$SqlCommand.(MapperMethod.java:225) 208 | at org.apache.ibatis.binding.MapperMethod.(MapperMethod.java:48) 209 | at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65) 210 | at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58) 211 | at com.sun.proxy.$Proxy68.login(Unknown Source) 212 | at com.example.security.controller.AuthController.login(AuthController.java:32) 213 | at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 214 | at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 215 | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 216 | at java.lang.reflect.Method.invoke(Method.java:498) 217 | at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) 218 | at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) 219 | at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) 220 | at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) 221 | at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) 222 | at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) 223 | at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) 224 | at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) 225 | at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) 226 | at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) 227 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) 228 | at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) 229 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) 230 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) 231 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 232 | at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) 233 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 234 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 235 | at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) 236 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 237 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 238 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 239 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) 240 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 241 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 242 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) 243 | at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) 244 | at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) 245 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 246 | at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) 247 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 248 | at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) 249 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 250 | at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) 251 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 252 | at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) 253 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 254 | at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) 255 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 256 | at com.example.security.jwt.JwtAuthenticationTokenFilter.doFilterInternal(JwtAuthenticationTokenFilter.java:55) 257 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 258 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 259 | at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) 260 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 261 | at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) 262 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 263 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 264 | at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) 265 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 266 | at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) 267 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 268 | at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 269 | at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) 270 | at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) 271 | at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347) 272 | at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263) 273 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 274 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 275 | at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) 276 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 277 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 278 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 279 | at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) 280 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 281 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 282 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 283 | at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) 284 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 285 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 286 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 287 | at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) 288 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 289 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) 290 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) 291 | at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) 292 | at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) 293 | at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) 294 | at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) 295 | at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) 296 | at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) 297 | at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) 298 | at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) 299 | at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) 300 | at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) 301 | at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) 302 | at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) 303 | at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) 304 | at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) 305 | at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) 306 | at java.lang.Thread.run(Thread.java:748) 307 | 【xkcoding】2019-01-05 21:51:30.851 ERROR [main] o.s.b.d.LoggingFailureAnalysisReporter - 308 | 309 | *************************** 310 | APPLICATION FAILED TO START 311 | *************************** 312 | 313 | Description: 314 | 315 | Field userService in com.example.security.controller.AuthController required a bean of type 'com.example.security.service.UserService' that could not be found. 316 | 317 | 318 | Action: 319 | 320 | Consider defining a bean of type 'com.example.security.service.UserService' in your configuration. 321 | 322 | 【xkcoding】2019-01-05 21:52:18.736 ERROR [main] o.s.b.d.LoggingFailureAnalysisReporter - 323 | 324 | *************************** 325 | APPLICATION FAILED TO START 326 | *************************** 327 | 328 | Description: 329 | 330 | Field userService in com.example.security.controller.AuthController required a bean of type 'com.example.security.service.UserService' that could not be found. 331 | 332 | 333 | Action: 334 | 335 | Consider defining a bean of type 'com.example.security.service.UserService' in your configuration. 336 | 337 | 【xkcoding】2019-01-05 23:05:44.143 ERROR [localhost-startStop-1] o.s.b.c.e.tomcat.TomcatStarter - Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'jwtAuthenticationTokenFilter': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jwtUserDetailsServiceImpl': Unsatisfied dependency expressed through field 'userMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userMapper' defined in file [C:\Users\37155\Documents\GitHub\springSecurityDemo\security\target\classes\com\example\security\mapper\UserMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database url for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "dev" are currently active). 338 | 【xkcoding】2019-01-05 23:05:44.209 ERROR [main] o.s.b.d.LoggingFailureAnalysisReporter - 339 | 340 | *************************** 341 | APPLICATION FAILED TO START 342 | *************************** 343 | 344 | Description: 345 | 346 | Cannot determine embedded database url for database type NONE 347 | 348 | Action: 349 | 350 | If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "dev" are currently active). 351 | 352 | 【xkcoding】2019-01-05 23:06:11.119 ERROR [localhost-startStop-1] o.s.b.c.e.tomcat.TomcatStarter - Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'jwtAuthenticationTokenFilter': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jwtUserDetailsServiceImpl': Unsatisfied dependency expressed through field 'userMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userMapper' defined in file [C:\Users\37155\Documents\GitHub\springSecurityDemo\security\target\classes\com\example\security\mapper\UserMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database url for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "dev" are currently active). 353 | 【xkcoding】2019-01-05 23:06:11.173 ERROR [main] o.s.b.d.LoggingFailureAnalysisReporter - 354 | 355 | *************************** 356 | APPLICATION FAILED TO START 357 | *************************** 358 | 359 | Description: 360 | 361 | Cannot determine embedded database url for database type NONE 362 | 363 | Action: 364 | 365 | If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "dev" are currently active). 366 | 367 | -------------------------------------------------------------------------------- /security/logs/error/online-study.2019-01-09.error: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ywbjja/springSecurity-jwt-vue-temple/1e742e7bac36f4370686782ca5dd28d4ee435675/security/logs/error/online-study.2019-01-09.error -------------------------------------------------------------------------------- /security/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | ########################################################################################## 204 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 205 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 206 | ########################################################################################## 207 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 208 | if [ "$MVNW_VERBOSE" = true ]; then 209 | echo "Found .mvn/wrapper/maven-wrapper.jar" 210 | fi 211 | else 212 | if [ "$MVNW_VERBOSE" = true ]; then 213 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 214 | fi 215 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 216 | while IFS="=" read key value; do 217 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 218 | esac 219 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 220 | if [ "$MVNW_VERBOSE" = true ]; then 221 | echo "Downloading from: $jarUrl" 222 | fi 223 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 224 | 225 | if command -v wget > /dev/null; then 226 | if [ "$MVNW_VERBOSE" = true ]; then 227 | echo "Found wget ... using wget" 228 | fi 229 | wget "$jarUrl" -O "$wrapperJarPath" 230 | elif command -v curl > /dev/null; then 231 | if [ "$MVNW_VERBOSE" = true ]; then 232 | echo "Found curl ... using curl" 233 | fi 234 | curl -o "$wrapperJarPath" "$jarUrl" 235 | else 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Falling back to using Java to download" 238 | fi 239 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 240 | if [ -e "$javaClass" ]; then 241 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 242 | if [ "$MVNW_VERBOSE" = true ]; then 243 | echo " - Compiling MavenWrapperDownloader.java ..." 244 | fi 245 | # Compiling the Java class 246 | ("$JAVA_HOME/bin/javac" "$javaClass") 247 | fi 248 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 249 | # Running the downloader 250 | if [ "$MVNW_VERBOSE" = true ]; then 251 | echo " - Running MavenWrapperDownloader.java ..." 252 | fi 253 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 254 | fi 255 | fi 256 | fi 257 | fi 258 | ########################################################################################## 259 | # End of extension 260 | ########################################################################################## 261 | 262 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 263 | if [ "$MVNW_VERBOSE" = true ]; then 264 | echo $MAVEN_PROJECTBASEDIR 265 | fi 266 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 267 | 268 | # For Cygwin, switch paths to Windows format before running java 269 | if $cygwin; then 270 | [ -n "$M2_HOME" ] && 271 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 272 | [ -n "$JAVA_HOME" ] && 273 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 274 | [ -n "$CLASSPATH" ] && 275 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 276 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 277 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 278 | fi 279 | 280 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 281 | 282 | exec "$JAVACMD" \ 283 | $MAVEN_OPTS \ 284 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 285 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 286 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 287 | -------------------------------------------------------------------------------- /security/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 124 | FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( 125 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | echo Found %WRAPPER_JAR% 132 | ) else ( 133 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 134 | echo Downloading from: %DOWNLOAD_URL% 135 | powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" 136 | echo Finished downloading %WRAPPER_JAR% 137 | ) 138 | @REM End of extension 139 | 140 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 141 | if ERRORLEVEL 1 goto error 142 | goto end 143 | 144 | :error 145 | set ERROR_CODE=1 146 | 147 | :end 148 | @endlocal & set ERROR_CODE=%ERROR_CODE% 149 | 150 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 151 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 152 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 153 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 154 | :skipRcPost 155 | 156 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 157 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 158 | 159 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 160 | 161 | exit /B %ERROR_CODE% 162 | -------------------------------------------------------------------------------- /security/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 1.5.9.RELEASE 9 | 10 | 11 | com.example 12 | security 13 | 0.0.1-SNAPSHOT 14 | security 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-security 25 | 26 | 27 | 28 | 29 | org.mybatis.spring.boot 30 | mybatis-spring-boot-starter 31 | 1.3.0 32 | 33 | 34 | 35 | mysql 36 | mysql-connector-java 37 | 8.0.11 38 | 39 | 40 | org.projectlombok 41 | lombok 42 | true 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-test 47 | test 48 | 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-web 53 | 54 | 55 | 56 | org.springframework.security 57 | spring-security-test 58 | test 59 | 60 | 61 | 62 | 63 | org.springframework.boot 64 | spring-boot-starter-data-redis 65 | 66 | 67 | 68 | 69 | 70 | org.apache.commons 71 | commons-lang3 72 | 3.7 73 | 74 | 75 | 76 | 77 | net.minidev 78 | json-smart 79 | 2.3 80 | compile 81 | 82 | 83 | 84 | 85 | io.jsonwebtoken 86 | jjwt 87 | 0.9.0 88 | 89 | 90 | 91 | 92 | ch.qos.logback 93 | logback-classic 94 | 1.2.3 95 | 96 | 97 | 98 | 99 | com.github.pagehelper 100 | pagehelper-spring-boot-starter 101 | 1.2.3 102 | 103 | 104 | 105 | 106 | 107 | commons-io 108 | commons-io 109 | 2.6 110 | 111 | 112 | 113 | 114 | commons-codec 115 | commons-codec 116 | 1.9 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | com.alibaba 125 | fastjson 126 | 1.2.56 127 | 128 | 129 | 130 | com.alibaba 131 | druid 132 | 1.0.29 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | org.springframework.boot 141 | spring-boot-maven-plugin 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/Exception/RewriteAccessDenyFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.security.Exception; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.example.security.util.RetCode; 5 | import com.example.security.util.RetResult; 6 | import org.springframework.security.access.AccessDeniedException; 7 | import org.springframework.security.web.access.AccessDeniedHandler; 8 | import org.springframework.stereotype.Component; 9 | 10 | import javax.servlet.ServletException; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | import java.io.IOException; 14 | 15 | /** 16 | * @Autoor:杨文彬 17 | * @Date:2019/1/28 18 | * @Description: 19 | */ 20 | @Component 21 | public class RewriteAccessDenyFilter implements AccessDeniedHandler { 22 | 23 | 24 | @Override 25 | public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException { 26 | RetResult retResult = new RetResult(RetCode.NODEFINED.getCode(),"抱歉,您没有访问该接口的权限"); 27 | httpServletResponse.setContentType("application/json;charset=utf-8"); 28 | httpServletResponse.setCharacterEncoding("UTF-8"); 29 | httpServletResponse.getWriter().write(JSON.toJSONString(retResult)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/SecurityApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.security; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.web.cors.CorsConfiguration; 8 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 9 | import org.springframework.web.filter.CorsFilter; 10 | 11 | @SpringBootApplication 12 | @MapperScan("com.example.security.mapper") 13 | public class SecurityApplication { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(SecurityApplication.class, args); 17 | } 18 | 19 | 20 | 21 | // 跨域 22 | @Bean 23 | public CorsFilter corsFilter() { 24 | final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 25 | final CorsConfiguration config = new CorsConfiguration(); 26 | config.setAllowCredentials(true); // 允许cookies跨域 27 | config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin 28 | config.addAllowedHeader("*");// #允许访问的头信息,*表示全部 29 | config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了 30 | config.addAllowedMethod("OPTIONS");// 允许提交请求的方法,*表示全部允许 31 | config.addAllowedMethod("HEAD"); 32 | config.addAllowedMethod("GET");// 允许Get的请求方法 33 | config.addAllowedMethod("PUT"); 34 | config.addAllowedMethod("POST"); 35 | config.addAllowedMethod("DELETE"); 36 | config.addAllowedMethod("PATCH"); 37 | source.registerCorsConfiguration("/**", config); 38 | return new CorsFilter(source); 39 | } 40 | 41 | } 42 | 43 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/config/CrossFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.security.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | 5 | import javax.servlet.*; 6 | import javax.servlet.http.HttpServletResponse; 7 | import java.io.IOException; 8 | 9 | //写一个filter对response进行过滤 10 | //@Configuration 11 | public class CrossFilter implements Filter { 12 | 13 | @Override 14 | public void destroy() { 15 | // TODO Auto-generated method stub 16 | 17 | } 18 | 19 | @Override 20 | public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 21 | throws IOException, ServletException { 22 | HttpServletResponse response = (HttpServletResponse) res; 23 | response.setHeader("Access-Control-Allow-Origin", "*"); 24 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 25 | response.setHeader("Access-Control-Max-Age", "3600"); 26 | response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With,x-requested-with, Content-Type, Accept, client_id, uuid, Authorization"); 27 | // response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); 28 | chain.doFilter(req, res); 29 | } 30 | 31 | @Override 32 | public void init(FilterConfig arg0) throws ServletException { 33 | 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/config/DruidDataSourceConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.example.security.config; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | import javax.sql.DataSource; 10 | import java.sql.SQLException; 11 | 12 | /** 13 | * @Autoor:杨文彬 14 | * @Date:2019/1/28 15 | * @Description: 16 | */ 17 | @Configuration 18 | @Slf4j 19 | public class DruidDataSourceConfigurer { 20 | @Value("${spring.datasource.url}") 21 | private String dbUrl; 22 | 23 | @Value("${spring.datasource.username}") 24 | private String username; 25 | 26 | @Value("${spring.datasource.password}") 27 | private String password; 28 | 29 | @Value("${spring.datasource.driver-class-name}") 30 | private String driverClassName; 31 | 32 | @Value("${spring.datasource.initialSize}") 33 | private int initialSize; 34 | 35 | @Value("${spring.datasource.minIdle}") 36 | private int minIdle; 37 | 38 | @Value("${spring.datasource.maxActive}") 39 | private int maxActive; 40 | 41 | @Value("${spring.datasource.maxWait}") 42 | private int maxWait; 43 | 44 | @Value("${spring.datasource.timeBetweenEvictionRunsMillis}") 45 | private int timeBetweenEvictionRunsMillis; 46 | 47 | @Value("${spring.datasource.minEvictableIdleTimeMillis}") 48 | private int minEvictableIdleTimeMillis; 49 | 50 | @Value("${spring.datasource.validationQuery}") 51 | private String validationQuery; 52 | 53 | @Value("${spring.datasource.testWhileIdle}") 54 | private boolean testWhileIdle; 55 | 56 | @Value("${spring.datasource.testOnBorrow}") 57 | private boolean testOnBorrow; 58 | 59 | @Value("${spring.datasource.testOnReturn}") 60 | private boolean testOnReturn; 61 | 62 | @Value("${spring.datasource.poolPreparedStatements}") 63 | private boolean poolPreparedStatements; 64 | 65 | @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}") 66 | private int maxPoolPreparedStatementPerConnectionSize; 67 | 68 | @Value("${spring.datasource.filters}") 69 | private String filters; 70 | 71 | @Value("{spring.datasource.connectionProperties}") 72 | private String connectionProperties; 73 | 74 | @Bean 75 | public DataSource getDataSource() { 76 | DruidDataSource datasource = new DruidDataSource(); 77 | datasource.setUrl(this.dbUrl); 78 | datasource.setUsername(username); 79 | datasource.setPassword(password); 80 | datasource.setDriverClassName(driverClassName); 81 | 82 | //configuration 83 | datasource.setInitialSize(initialSize); 84 | datasource.setMinIdle(minIdle); 85 | datasource.setMaxActive(maxActive); 86 | datasource.setMaxWait(maxWait); 87 | datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); 88 | datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); 89 | datasource.setValidationQuery(validationQuery); 90 | datasource.setTestWhileIdle(testWhileIdle); 91 | datasource.setTestOnBorrow(testOnBorrow); 92 | datasource.setTestOnReturn(testOnReturn); 93 | datasource.setPoolPreparedStatements(poolPreparedStatements); 94 | datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); 95 | try { 96 | datasource.setFilters(filters); 97 | } catch (SQLException e) { 98 | log.error("druid configuration initialization filter", e); 99 | } 100 | datasource.setConnectionProperties(connectionProperties); 101 | 102 | return datasource; 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/config/DruidMonitorConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.example.security.config; 2 | 3 | import com.alibaba.druid.support.http.StatViewServlet; 4 | import com.alibaba.druid.support.http.WebStatFilter; 5 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 6 | import org.springframework.boot.web.servlet.ServletRegistrationBean; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | /** 11 | * @Autoor:杨文彬 12 | * @Date:2019/1/28 13 | * @Description: 14 | */ 15 | @Configuration 16 | public class DruidMonitorConfigurer { 17 | /** 18 | * 注册ServletRegistrationBean 19 | * @return 20 | */ 21 | @Bean 22 | public ServletRegistrationBean registrationBean() { 23 | ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); 24 | /** 初始化参数配置,initParams**/ 25 | //白名单 26 | bean.addInitParameter("allow", "127.0.0.1");//多个ip逗号隔开 27 | //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page. 28 | //登录查看信息的账号密码. 29 | bean.addInitParameter("loginUsername", "admin"); 30 | bean.addInitParameter("loginPassword", "123456"); 31 | //是否能够重置数据. 32 | bean.addInitParameter("resetEnable", "false"); 33 | return bean; 34 | } 35 | 36 | /** 37 | * 注册FilterRegistrationBean 38 | * @return 39 | */ 40 | @Bean 41 | public FilterRegistrationBean druidStatFilter() { 42 | FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter()); 43 | //添加过滤规则. 44 | bean.addUrlPatterns("/*"); 45 | //添加不需要忽略的格式信息. 46 | bean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); 47 | return bean; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/config/RedisConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.example.security.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.redis.connection.RedisConnectionFactory; 6 | import org.springframework.data.redis.core.RedisTemplate; 7 | import org.springframework.data.redis.serializer.StringRedisSerializer; 8 | 9 | /** 10 | * @Autoor:杨文彬 11 | * @Date:2019/2/21 12 | * @Description: 13 | */ 14 | @Configuration 15 | public class RedisConfigurer { 16 | @Bean 17 | public RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory){ 18 | RedisTemplate redisTemplate = new RedisTemplate<>(); 19 | redisTemplate.setConnectionFactory(redisConnectionFactory); 20 | redisTemplate.setValueSerializer(new StringRedisSerializer()); 21 | redisTemplate.setKeySerializer(new StringRedisSerializer()); 22 | redisTemplate.setHashKeySerializer(new StringRedisSerializer()); 23 | redisTemplate.setHashValueSerializer(new StringRedisSerializer()); 24 | return redisTemplate; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/config/WebSecurity.java: -------------------------------------------------------------------------------- 1 | package com.example.security.config; 2 | 3 | import com.example.security.Exception.RewriteAccessDenyFilter; 4 | import com.example.security.jwt.JwtAuthenticationTokenFilter; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.http.HttpMethod; 9 | import org.springframework.security.authentication.AuthenticationManager; 10 | import org.springframework.security.config.BeanIds; 11 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 12 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 13 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 15 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 16 | import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; 17 | import org.springframework.security.config.http.SessionCreationPolicy; 18 | import org.springframework.security.core.userdetails.UserDetailsService; 19 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 20 | import org.springframework.security.crypto.password.PasswordEncoder; 21 | import org.springframework.security.web.access.ExceptionTranslationFilter; 22 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 23 | import org.springframework.web.cors.CorsConfiguration; 24 | import org.springframework.web.cors.CorsUtils; 25 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 26 | import org.springframework.web.filter.CorsFilter; 27 | 28 | /** 29 | * @Autoor:杨文彬 30 | * @Date:2019/1/4 31 | * @Description: 32 | */ 33 | @EnableWebSecurity 34 | @EnableGlobalMethodSecurity(prePostEnabled = true) 35 | public class WebSecurity extends WebSecurityConfigurerAdapter { 36 | 37 | @Autowired 38 | private UserDetailsService userDetailsService; 39 | 40 | @Autowired 41 | private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; 42 | 43 | //自定义无权限访问拦截器 44 | @Autowired 45 | private RewriteAccessDenyFilter rewriteAccessDenyFilter; 46 | 47 | @Autowired 48 | public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder)throws Exception{ 49 | authenticationManagerBuilder.userDetailsService(this.userDetailsService).passwordEncoder(passwordEncoder()); 50 | } 51 | 52 | 53 | @Bean(name = BeanIds.AUTHENTICATION_MANAGER) 54 | @Override 55 | public AuthenticationManager authenticationManagerBean() throws Exception { 56 | return super.authenticationManagerBean(); 57 | } 58 | 59 | @Bean 60 | public PasswordEncoder passwordEncoder() { 61 | return new BCryptPasswordEncoder(); 62 | } 63 | 64 | @Override 65 | protected void configure(HttpSecurity http) throws Exception { 66 | 67 | http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 68 | .and().authorizeRequests() 69 | .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() 70 | .antMatchers("/auth/**").permitAll() 71 | .antMatchers("/druid/**").anonymous() 72 | .anyRequest().authenticated() 73 | .and().headers().cacheControl(); 74 | 75 | http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); 76 | http.exceptionHandling().accessDeniedHandler(rewriteAccessDenyFilter); 77 | 78 | 79 | ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry registry = http.authorizeRequests(); 80 | //让Spring security放行所有preflight request 81 | registry.requestMatchers(CorsUtils::isPreFlightRequest).permitAll(); 82 | } 83 | 84 | // @Bean 85 | // public CorsFilter corsFilter() { 86 | // final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); 87 | // final CorsConfiguration cors = new CorsConfiguration(); 88 | // cors.setAllowCredentials(true); 89 | // cors.addAllowedOrigin("https://vue.antywb.com/api_v1"); 90 | // cors.addAllowedHeader("*"); 91 | // cors.addAllowedMethod("*"); 92 | // urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", cors); 93 | // return new CorsFilter(urlBasedCorsConfigurationSource); 94 | // } 95 | } 96 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/controller/AuthController.java: -------------------------------------------------------------------------------- 1 | package com.example.security.controller; 2 | 3 | import com.example.security.service.UserService; 4 | import com.example.security.util.RetResult; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Qualifier; 7 | import org.springframework.web.bind.annotation.RequestBody; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestMethod; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import javax.annotation.Resource; 13 | import javax.naming.Name; 14 | import java.util.Map; 15 | 16 | /** 17 | * @Autoor:杨文彬 18 | * @Date:2019/1/4 19 | * @Description: 20 | */ 21 | @RestController 22 | public class AuthController { 23 | 24 | 25 | @Autowired 26 | private UserService userService; 27 | 28 | @RequestMapping(value = "${jwt.route.login}",method = RequestMethod.POST) 29 | public RetResult login(@RequestBody Map map){ 30 | String username = map.get("username").toString(); 31 | String passwordAES = map.get("password").toString(); 32 | return userService.login(username,passwordAES); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/controller/PermissionController.java: -------------------------------------------------------------------------------- 1 | package com.example.security.controller; 2 | 3 | import com.example.security.service.PermissionService; 4 | import com.example.security.util.RetCode; 5 | import com.example.security.util.RetResult; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.security.access.prepost.PreAuthorize; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | 14 | /** 15 | * @Autoor:杨文彬 16 | * @Date:2019/1/22 17 | * @Description: 18 | */ 19 | @Slf4j 20 | @RestController 21 | @CrossOrigin(origins = "*", allowCredentials= "true") 22 | public class PermissionController { 23 | 24 | @Autowired 25 | private PermissionService permissionService; 26 | 27 | /** 28 | * 更新菜单菜单 29 | * @param map 30 | * @return 31 | */ 32 | @PreAuthorize("hasAnyRole('ADMIN')") 33 | @PutMapping(value = "/menus") 34 | public RetResult getRoleList(@RequestBody Map map){ 35 | return permissionService.update(map); 36 | } 37 | 38 | /** 39 | * 添加菜单 40 | * @param map 41 | * @return 42 | */ 43 | @PreAuthorize("hasAnyRole('ADMIN')") 44 | @PostMapping(value = "/menus") 45 | public RetResult addPermisson(@RequestBody Map map){ 46 | return permissionService.add(map); 47 | } 48 | 49 | 50 | /** 51 | * 删除菜单 52 | * @param per_id 53 | * @return 54 | */ 55 | @PreAuthorize("hasAnyRole('ADMIN')") 56 | @DeleteMapping(value = "/menus/{per_id}") 57 | public RetResult delPermission(@PathVariable Long per_id){ 58 | Map map = new HashMap<>(); 59 | map.put("per_id",per_id); 60 | return permissionService.del(map); 61 | } 62 | 63 | /** 64 | * 获取所有菜单(树形表格数据) 65 | * @param map 66 | * @return 67 | */ 68 | @PreAuthorize("hasAnyRole('ADMIN')") 69 | @PostMapping(value = "/getMenusTableTree") 70 | public RetResult getMenusTableTree(@RequestBody(required = false) Map map){ 71 | //使用Spring Security 获取用户信息 72 | return new RetResult(RetCode.SUCCESS.getCode(),permissionService.queryAllMenusTree(map)); 73 | } 74 | 75 | /** 76 | * 获取角色对应的id集合 77 | * @param map 78 | * @return 79 | */ 80 | @PreAuthorize("hasAnyRole('ADMIN')") 81 | @PostMapping(value = "/getPerIdList") 82 | public RetResult getPerIdList(@RequestBody Map map){ 83 | //使用Spring Security 获取用户信息 84 | return new RetResult(RetCode.SUCCESS.getCode(),permissionService.getPerIdList(map)); 85 | } 86 | 87 | 88 | /** 89 | * 获取角色对应的id集合 90 | * @param map 91 | * @return 92 | */ 93 | @PreAuthorize("hasAnyRole('ADMIN')") 94 | @PutMapping(value = "/perms") 95 | public RetResult addPerms(@RequestBody Map map){ 96 | //使用Spring Security 获取用户信息 97 | return new RetResult(RetCode.SUCCESS.getCode(),permissionService.addRP(map)); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/controller/RoleController.java: -------------------------------------------------------------------------------- 1 | package com.example.security.controller; 2 | 3 | import com.example.security.service.RoleService; 4 | import com.example.security.util.RetCode; 5 | import com.example.security.util.RetResult; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Required; 9 | import org.springframework.security.access.prepost.PreAuthorize; 10 | import org.springframework.web.bind.annotation.*; 11 | 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | /** 16 | * @Autoor:杨文彬 17 | * @Date:2019/1/21 18 | * @Description: 19 | */ 20 | @Slf4j 21 | @RestController 22 | @CrossOrigin(origins = "*", allowCredentials= "true") 23 | public class RoleController { 24 | 25 | @Autowired 26 | private RoleService roleService; 27 | 28 | /** 29 | * 更新角色信息 30 | * @param map 31 | * @return 32 | */ 33 | @PreAuthorize("hasAnyRole('ADMIN')") 34 | @PutMapping(value = "/roles") 35 | public RetResult update(@RequestBody Map map){ 36 | return roleService.updateById(map); 37 | } 38 | 39 | /** 40 | * 删除角色 41 | * @param id 42 | * @return 43 | */ 44 | @PreAuthorize("hasAnyRole('ADMIN')") 45 | @DeleteMapping(value = "/roles/{id}") 46 | public RetResult del(@PathVariable Long id){ 47 | Map map = new HashMap<>(); 48 | map.put("id",id); 49 | return roleService.delRoleById(map); 50 | } 51 | 52 | /** 53 | * 添加角色 54 | * @param map 55 | * @return 56 | */ 57 | @PreAuthorize("hasAnyRole('ADMIN')") 58 | @PostMapping(value = "/roles") 59 | public RetResult add(@RequestBody Map map){ 60 | return roleService.addRoleById(map); 61 | } 62 | 63 | /** 64 | * 获取角色列表 65 | * @param map 66 | * @return 67 | */ 68 | @PreAuthorize("hasAnyRole('ADMIN')") 69 | @RequestMapping(value = "/getRoleList",method = RequestMethod.POST) 70 | public RetResult getRoleList(@RequestBody Map map){ 71 | return roleService.getRoleListByCond(map); 72 | } 73 | 74 | /** 75 | * 获取全部角色列表 76 | * @param map 77 | * @return 78 | */ 79 | @PreAuthorize("hasAnyRole('ADMIN')") 80 | @RequestMapping(value = "/getAllRoleList",method = RequestMethod.POST) 81 | public RetResult getAllRoleList(@RequestBody(required = false) Map map){ 82 | return roleService.getAllRoleList(map); 83 | } 84 | 85 | /** 86 | * 根据权限id查询角色列表 87 | * @param map 88 | * @return 89 | */ 90 | @PreAuthorize("hasAnyRole('ADMIN')") 91 | @PostMapping(value = "/getRoleListByPerId") 92 | public RetResult getRoleListByPerId(@RequestBody(required = false) Map map){ 93 | return roleService.getRoleListByPerId(map); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.example.security.controller; 2 | 3 | import com.example.security.service.UserService; 4 | import com.example.security.util.RetCode; 5 | import com.example.security.util.RetResult; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.security.access.prepost.PreAuthorize; 9 | import org.springframework.security.core.context.SecurityContextHolder; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.web.bind.annotation.CrossOrigin; 12 | import org.springframework.web.bind.annotation.RequestBody; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RestController; 15 | import org.springframework.web.method.annotation.ModelAttributeMethodProcessor; 16 | 17 | import java.util.Map; 18 | 19 | /** 20 | * @Autoor:杨文彬 21 | * @Date:2019/1/7 22 | * @Description: 23 | */ 24 | @Slf4j 25 | @RestController 26 | @CrossOrigin(origins = "*", allowCredentials= "true") 27 | public class UserController { 28 | 29 | @Autowired 30 | private UserService userService; 31 | 32 | 33 | /** 34 | * 通过token获取用户信息 35 | * @param map 36 | * @return 37 | */ 38 | @RequestMapping(value = "/getUserInfo") 39 | public RetResult getUserInfo(@RequestBody(required = false) Mapmap){ 40 | //使用Spring Security 获取用户信息 41 | UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 42 | log.info(userDetails.getUsername()); 43 | return userService.getUserInfo(userDetails.getUsername()); 44 | } 45 | 46 | 47 | /** 48 | * 获取当前用户下的路由菜单 49 | * @param map 50 | * @return 51 | */ 52 | @PreAuthorize("hasAnyRole('ADMIN')") 53 | @RequestMapping(value = "/queryMenuTree") 54 | public RetResult getMenuTree(@RequestBody(required = false) Map map){ 55 | //使用Spring Security 获取用户信息 56 | UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 57 | log.info(userDetails.getUsername()); 58 | return userService.getMenuTree(userDetails.getUsername()); 59 | } 60 | 61 | 62 | /** 63 | * 获取所有的菜单并返回菜单树 64 | * @param map 65 | * @return 66 | */ 67 | @PreAuthorize("hasAnyRole('ADMIN')") 68 | @RequestMapping(value = "/getAllMenuTree") 69 | public RetResult getAllMenuTree(@RequestBody(required = false) Map map){ 70 | //使用Spring Security 获取用户信息 71 | return new RetResult(RetCode.SUCCESS.getCode(),userService.getAllMenuTree(userService.getMenuTreeByPid(Long.parseLong("0")))); 72 | } 73 | 74 | 75 | 76 | } 77 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/entity/Permission.java: -------------------------------------------------------------------------------- 1 | package com.example.security.entity; 2 | 3 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 4 | import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; 5 | import lombok.Data; 6 | 7 | import java.sql.Time; 8 | import java.sql.Timestamp; 9 | import java.time.LocalDateTime; 10 | import java.util.List; 11 | import java.util.Map; 12 | import java.util.Set; 13 | 14 | /** 15 | * @Autoor:杨文彬 16 | * @Date:2019/1/7 17 | * @Description: 18 | */ 19 | @Data 20 | public class Permission { 21 | 22 | 23 | @JsonSerialize(using = ToStringSerializer.class) 24 | private Long per_id; 25 | @JsonSerialize(using = ToStringSerializer.class) 26 | private Long per_parent_id; 27 | private String per_name; 28 | private String per_resource; 29 | private String per_type; 30 | private String per_icon; 31 | private String per_describe; 32 | private String per_component; 33 | private Integer per_sort; 34 | private Timestamp per_crtTime; 35 | private List children; 36 | 37 | public Permission() { 38 | } 39 | 40 | public Permission(Long per_id, Long per_parent_id, String per_name, String per_resource, String per_type, String per_icon, String per_describe, String per_component, 41 | Integer per_sort, Timestamp per_crtTime ,List children) { 42 | this.per_id = per_id; 43 | this.per_parent_id = per_parent_id; 44 | this.per_name = per_name; 45 | this.per_resource = per_resource; 46 | this.per_type = per_type; 47 | this.per_icon = per_icon; 48 | this.per_describe = per_describe; 49 | this.per_component = per_component; 50 | this.per_sort = per_sort; 51 | this.per_crtTime = per_crtTime; 52 | this.children = children; 53 | } 54 | public Permission(Map map){ 55 | if(map.get("per_id") != null){ 56 | this.per_id = Long.valueOf(map.get("per_id").toString()); 57 | } else { 58 | this.per_id = null; 59 | } 60 | this.per_name = (String)map.get("per_name"); 61 | if (map.get("per_parent_id") != null) { 62 | this.per_parent_id = Long.valueOf(map.get("per_parent_id").toString()); 63 | } else { 64 | this.per_parent_id = null; 65 | } 66 | this.per_resource = (String)map.get("per_resource"); 67 | this.per_type = (String)map.get("per_per_type"); 68 | this.per_icon = (String)map.get("per_icon"); 69 | this.per_describe = (String)map.get("per_describe"); 70 | this.per_component = (String)map.get("per_component"); 71 | this.per_sort = (Integer)map.get("per_sort"); 72 | if(map.get("per_crtTime") != null){ 73 | this.per_crtTime = Timestamp.valueOf(map.get("per_crtTime").toString()); 74 | } else { 75 | this.per_crtTime = null; 76 | } 77 | 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/entity/Role.java: -------------------------------------------------------------------------------- 1 | package com.example.security.entity; 2 | 3 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 4 | import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; 5 | import lombok.Data; 6 | 7 | import java.sql.Timestamp; 8 | import java.util.ArrayList; 9 | import java.util.Date; 10 | import java.util.Set; 11 | 12 | /** 13 | * @Autoor:杨文彬 14 | * @Date:2019/1/4 15 | * @Description: 16 | */ 17 | @Data 18 | public class Role { 19 | 20 | @JsonSerialize(using = ToStringSerializer.class) 21 | private Long id; 22 | 23 | 24 | private String rolename; 25 | 26 | private String roledesc; 27 | 28 | private Timestamp createTime; 29 | 30 | 31 | //权限的列表 32 | private ArrayList permissions; 33 | 34 | public Role() { 35 | } 36 | 37 | public Role(Long id, String rolename, String roledesc, Timestamp createTime, ArrayList permissions) { 38 | this.id = id; 39 | this.rolename = rolename; 40 | this.roledesc = roledesc; 41 | this.createTime = createTime; 42 | this.permissions = permissions; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/entity/RolePermission.java: -------------------------------------------------------------------------------- 1 | package com.example.security.entity; 2 | 3 | import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; 4 | import lombok.Data; 5 | 6 | import java.util.Map; 7 | 8 | /** 9 | * @Autoor:杨文彬 10 | * @Date:2019/1/24 11 | * @Description: 12 | */ 13 | @Data 14 | public class RolePermission { 15 | 16 | private Long rp_id; 17 | private Long rp_per_id; 18 | private Long rp_role_id; 19 | 20 | public RolePermission(Map map) { 21 | if(map.get("rp_id") != null){ 22 | this.rp_id = Long.valueOf(map.get("rp_id").toString()); 23 | } else { 24 | this.rp_id = null; 25 | } 26 | if(map.get("rp_per_id") != null){ 27 | this.rp_per_id = Long.valueOf(map.get("rp_per_id").toString()); 28 | } else { 29 | this.rp_per_id = null; 30 | } 31 | if(map.get("rp_role_id") != null){ 32 | this.rp_role_id = Long.valueOf(map.get("rp_role_id").toString()); 33 | } else { 34 | this.rp_role_id = null; 35 | } 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.example.security.entity; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | import java.util.Date; 7 | import java.util.Set; 8 | 9 | /** 10 | * @Autoor:杨文彬 11 | * @Date:2019/1/4 12 | * @Description: 13 | */ 14 | @Data 15 | public class User implements Serializable { 16 | 17 | private String id; 18 | 19 | private String avatar; 20 | 21 | private String username; 22 | 23 | private String password; 24 | 25 | private String phone; 26 | 27 | 28 | private Integer state; 29 | 30 | 31 | 32 | private Set roles; 33 | } 34 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/jwt/JwtAuthenticationTokenFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.security.jwt; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.example.security.mapper.UserMapper; 5 | import com.example.security.util.RedisUtil; 6 | import com.example.security.util.RetCode; 7 | import com.example.security.util.RetResult; 8 | import io.jsonwebtoken.ExpiredJwtException; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.apache.commons.lang3.StringUtils; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 13 | import org.springframework.security.core.context.SecurityContextHolder; 14 | import org.springframework.security.core.userdetails.UserDetails; 15 | import org.springframework.security.core.userdetails.UserDetailsService; 16 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 17 | import org.springframework.stereotype.Component; 18 | import org.springframework.web.filter.OncePerRequestFilter; 19 | 20 | import javax.annotation.Resource; 21 | import javax.servlet.FilterChain; 22 | import javax.servlet.ServletException; 23 | import javax.servlet.http.HttpServletRequest; 24 | import javax.servlet.http.HttpServletResponse; 25 | import java.io.IOException; 26 | import java.util.Date; 27 | import java.util.HashMap; 28 | import java.util.Map; 29 | 30 | /** 31 | * @Autoor:杨文彬 32 | * @Date:2019/1/4 33 | * @Description: 34 | */ 35 | @Slf4j 36 | @Component 37 | public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { 38 | 39 | 40 | 41 | @Autowired 42 | private UserDetailsService userDetailsService; 43 | 44 | @Autowired 45 | private JwtTokenUtil jwtTokenUtil; 46 | 47 | @Resource 48 | private RedisUtil redisUtil; 49 | 50 | @Autowired 51 | private UserMapper userMapper; 52 | 53 | 54 | @Override 55 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) { 56 | String authHeader = request.getHeader(jwtTokenUtil.getHeader()); 57 | try { 58 | if (authHeader != null && StringUtils.isNotEmpty(authHeader)) { 59 | String username = jwtTokenUtil.getUsernameFromToken(authHeader); 60 | jwtTokenUtil.validateToken(authHeader);//验证令牌 61 | if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { 62 | UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); 63 | if (jwtTokenUtil.validateToken(authHeader)) { 64 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); 65 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 66 | SecurityContextHolder.getContext().setAuthentication(authentication); 67 | } 68 | } 69 | } 70 | chain.doFilter(request, response); 71 | } 72 | catch (ExpiredJwtException e){ 73 | e.printStackTrace(); 74 | Map map = jwtTokenUtil.parseJwtPayload(authHeader); 75 | String userid = (String)map.get("userid"); 76 | //这里的方案是如果令牌过期了,先去判断redis中存储的令牌是否过期,如果过期就重新登录,如果redis中存储的没有过期就可以 77 | //继续生成token返回给前端存储方式key:userid,value:令牌 78 | String redisResult = redisUtil.get(userid); 79 | String username= (String) map.get("sub"); 80 | if(StringUtils.isNoneEmpty(redisResult)){ 81 | JwtUser jwtUser = new JwtUser(); 82 | jwtUser.setUserid(userid); 83 | jwtUser.setUsername(username); 84 | Map claims = new HashMap<>(2); 85 | claims.put("sub", jwtUser.getUsername()); 86 | claims.put("userid", jwtUser.getUserid()); 87 | claims.put("created", new Date()); 88 | String token = jwtTokenUtil.generateToken(jwtUser); 89 | //更新redis中的token 90 | //首先获取key的有效期,把新的token的有效期设为旧的token剩余的有效期 91 | redisUtil.setAndTime(userid,token,redisUtil.getExpireTime(userid)); 92 | if (token != null && StringUtils.isNotEmpty(token)) { 93 | jwtTokenUtil.validateToken(token);//验证令牌 94 | if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { 95 | UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); 96 | if (jwtTokenUtil.validateToken(token)) { 97 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); 98 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 99 | SecurityContextHolder.getContext().setAuthentication(authentication); 100 | } 101 | } 102 | } 103 | response.setHeader("newToken",token); 104 | response.addHeader("Access-Control-Expose-Headers","newToken"); 105 | response.setContentType("application/json;charset=utf-8"); 106 | response.setCharacterEncoding("UTF-8"); 107 | try { 108 | chain.doFilter(request, response); 109 | } catch (IOException e1) { 110 | e1.printStackTrace(); 111 | } catch (ServletException e1) { 112 | e1.printStackTrace(); 113 | } 114 | 115 | } else { 116 | response.addHeader("Access-Control-Allow-origin","http://localhost:9528"); 117 | RetResult retResult = new RetResult(RetCode.EXPIRED.getCode(),"抱歉,您的登录信息已过期,请重新登录"); 118 | response.setContentType("application/json;charset=utf-8"); 119 | response.setCharacterEncoding("UTF-8"); 120 | try { 121 | response.getWriter().write(JSON.toJSONString(retResult)); 122 | } catch (IOException e1) { 123 | e1.printStackTrace(); 124 | } 125 | System.out.println("redis过期"); 126 | } 127 | } catch (ServletException e) { 128 | e.printStackTrace(); 129 | } catch (IOException e) { 130 | e.printStackTrace(); 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/jwt/JwtTokenUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.security.jwt; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import io.jsonwebtoken.*; 6 | import io.jsonwebtoken.impl.DefaultHeader; 7 | import io.jsonwebtoken.impl.DefaultJwsHeader; 8 | import io.jsonwebtoken.impl.TextCodec; 9 | import io.jsonwebtoken.impl.compression.DefaultCompressionCodecResolver; 10 | import io.jsonwebtoken.lang.Assert; 11 | import lombok.Data; 12 | import lombok.extern.slf4j.Slf4j; 13 | import org.springframework.boot.context.properties.ConfigurationProperties; 14 | import org.springframework.security.core.userdetails.UserDetails; 15 | import org.springframework.stereotype.Component; 16 | 17 | import java.io.IOException; 18 | import java.io.Serializable; 19 | import java.util.Date; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | /** 24 | * @Autoor:杨文彬 25 | * @Date:2019/1/4 26 | * @Description: 27 | */ 28 | @Data 29 | @Slf4j 30 | @ConfigurationProperties(prefix = "jwt") 31 | @Component 32 | public class JwtTokenUtil implements Serializable { 33 | 34 | private String secret; 35 | 36 | private Long expiration; 37 | 38 | private String header; 39 | 40 | private static final ObjectMapper MAPPER = new ObjectMapper(); 41 | 42 | private static CompressionCodecResolver codecResolver = new DefaultCompressionCodecResolver(); 43 | 44 | /** 45 | * 从数据声明生成令牌 46 | * 47 | * @param claims 数据声明 48 | * @return 令牌 49 | */ 50 | private String generateToken(Map claims) { 51 | Date expirationDate = new Date(System.currentTimeMillis() + expiration); 52 | return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, secret).compact(); 53 | } 54 | 55 | 56 | public static Map parseJwtPayload(String jwt) { 57 | Assert.hasText(jwt, "JWT String argument cannot be null or empty."); 58 | String base64UrlEncodedHeader = null; 59 | String base64UrlEncodedPayload = null; 60 | String base64UrlEncodedDigest = null; 61 | int delimiterCount = 0; 62 | StringBuilder sb = new StringBuilder(128); 63 | for (char c : jwt.toCharArray()) { 64 | if (c == '.') { 65 | CharSequence tokenSeq = io.jsonwebtoken.lang.Strings.clean(sb); 66 | String token = tokenSeq != null ? tokenSeq.toString() : null; 67 | 68 | if (delimiterCount == 0) { 69 | base64UrlEncodedHeader = token; 70 | } else if (delimiterCount == 1) { 71 | base64UrlEncodedPayload = token; 72 | } 73 | 74 | delimiterCount++; 75 | sb.setLength(0); 76 | } else { 77 | sb.append(c); 78 | } 79 | } 80 | if (delimiterCount != 2) { 81 | String msg = "JWT strings must contain exactly 2 period characters. Found: " + delimiterCount; 82 | throw new MalformedJwtException(msg); 83 | } 84 | if (sb.length() > 0) { 85 | base64UrlEncodedDigest = sb.toString(); 86 | } 87 | if (base64UrlEncodedPayload == null) { 88 | throw new MalformedJwtException("JWT string '" + jwt + "' is missing a body/payload."); 89 | } 90 | // =============== Header ================= 91 | Header header = null; 92 | CompressionCodec compressionCodec = null; 93 | if (base64UrlEncodedHeader != null) { 94 | String origValue = TextCodec.BASE64URL.decodeToString(base64UrlEncodedHeader); 95 | Map m = readValue(origValue); 96 | if (base64UrlEncodedDigest != null) { 97 | header = new DefaultJwsHeader(m); 98 | } else { 99 | header = new DefaultHeader(m); 100 | } 101 | compressionCodec = codecResolver.resolveCompressionCodec(header); 102 | } 103 | // =============== Body ================= 104 | String payload; 105 | if (compressionCodec != null) { 106 | byte[] decompressed = compressionCodec.decompress(TextCodec.BASE64URL.decode(base64UrlEncodedPayload)); 107 | payload = new String(decompressed, io.jsonwebtoken.lang.Strings.UTF_8); 108 | } else { 109 | payload = TextCodec.BASE64URL.decodeToString(base64UrlEncodedPayload); 110 | } 111 | JSONObject jsonObject = JSONObject.parseObject(payload); 112 | Map map = jsonObject; 113 | return map; 114 | } 115 | 116 | 117 | /* * 118 | * @Description 119 | * @Param [val] 从json数据中读取格式化map 120 | * @Return java.util.Map 121 | */ 122 | public static Map readValue(String val) { 123 | try { 124 | return MAPPER.readValue(val, Map.class); 125 | } catch (IOException e) { 126 | throw new MalformedJwtException("Unable to read JSON value: " + val, e); 127 | } 128 | } 129 | 130 | 131 | /** 132 | * 从令牌中获取数据声明 133 | * 134 | * @param token 令牌 135 | * @return 数据声明 136 | */ 137 | public Claims getClaimsFromToken(String token) { 138 | Claims claims; 139 | try { 140 | claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); 141 | } catch (Exception e) { 142 | claims = null; 143 | } 144 | return claims; 145 | } 146 | 147 | /** 148 | * 生成令牌 149 | * 150 | * @param jwtUser 用户 151 | * @return 令牌 152 | */ 153 | public String generateToken(JwtUser jwtUser) { 154 | Map claims = new HashMap<>(2); 155 | claims.put("sub", jwtUser.getUsername()); 156 | claims.put("userid", jwtUser.getUserid()); 157 | claims.put("created", new Date()); 158 | return generateToken(claims); 159 | } 160 | 161 | /** 162 | * 从令牌中获取用户名 163 | * 164 | * @param token 令牌 165 | * @return 用户名 166 | */ 167 | public String getUsernameFromToken(String token) { 168 | String username; 169 | try { 170 | Claims claims = getClaimsFromToken(token); 171 | username = claims.getSubject(); 172 | } catch (Exception e) { 173 | username = null; 174 | } 175 | return username; 176 | } 177 | 178 | /** 179 | * 从令牌中获取用户id 180 | * 181 | * @param token 令牌 182 | * @return 用户名 183 | */ 184 | public String getUseridFromToken(String token) { 185 | String userid; 186 | try { 187 | Claims claims = getClaimsFromToken(token); 188 | userid = (String) claims.get("userid"); 189 | } catch (Exception e) { 190 | userid = null; 191 | } 192 | return userid; 193 | } 194 | 195 | /** 196 | * 判断令牌是否过期 197 | * 198 | * @param token 令牌 199 | * @return 是否过期 200 | */ 201 | public Boolean isTokenExpired(String token) { 202 | try { 203 | Claims claims = getClaimsFromToken(token); 204 | Date expiration = claims.getExpiration(); 205 | return expiration.before(new Date()); 206 | } catch (Exception e) { 207 | return false; 208 | } 209 | } 210 | 211 | /** 212 | * 刷新令牌 213 | * 214 | * @param token 原令牌 215 | * @return 新令牌 216 | */ 217 | public String refreshToken(String token) { 218 | String refreshedToken; 219 | try { 220 | Claims claims = getClaimsFromToken(token); 221 | claims.put("created", new Date()); 222 | refreshedToken = generateToken(claims); 223 | } catch (Exception e) { 224 | e.printStackTrace(); 225 | log.info(e.getMessage()); 226 | refreshedToken = null; 227 | } 228 | return refreshedToken; 229 | } 230 | 231 | /** 232 | * 验证令牌 233 | * 234 | * @param token 令牌 235 | * @param 236 | * @return 是否有效 237 | */ 238 | public Boolean validateToken(String token) { 239 | try { 240 | Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); 241 | return true; 242 | } catch (ExpiredJwtException e) { 243 | log.info(e.getMessage()); 244 | throw e; 245 | } 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/jwt/JwtUser.java: -------------------------------------------------------------------------------- 1 | package com.example.security.jwt; 2 | 3 | import lombok.Data; 4 | import net.minidev.json.annotate.JsonIgnore; 5 | import org.springframework.security.core.GrantedAuthority; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | 8 | import java.util.Collection; 9 | 10 | /** 11 | * @Autoor:杨文彬 12 | * @Date:2019/1/4 13 | * @Description: 14 | */ 15 | @Data 16 | public class JwtUser implements UserDetails { 17 | 18 | private String userid; 19 | 20 | private String username; 21 | 22 | private String password; 23 | 24 | private Integer state; 25 | 26 | private Collection authorities; 27 | 28 | public JwtUser() { 29 | } 30 | 31 | public JwtUser(String userid,String username, String password, Integer state, Collection authorities) { 32 | this.userid = userid; 33 | this.username = username; 34 | this.password = password; 35 | this.state = state; 36 | this.authorities = authorities; 37 | } 38 | 39 | 40 | @Override 41 | public String getUsername() { 42 | return username; 43 | } 44 | 45 | @JsonIgnore 46 | @Override 47 | public String getPassword() { 48 | return password; 49 | } 50 | 51 | @Override 52 | public Collection getAuthorities() { 53 | return authorities; 54 | } 55 | 56 | //账户是否未过期 57 | @JsonIgnore 58 | @Override 59 | public boolean isAccountNonExpired() { 60 | return true; 61 | } 62 | 63 | //账户是否未被锁 64 | @Override 65 | public boolean isAccountNonLocked() { 66 | return true; 67 | } 68 | 69 | 70 | 71 | @JsonIgnore 72 | @Override 73 | public boolean isCredentialsNonExpired() { 74 | return true; 75 | } 76 | 77 | 78 | //是否启用 79 | @JsonIgnore 80 | @Override 81 | public boolean isEnabled() { 82 | return true; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/mapper/PermissionMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.security.mapper; 2 | 3 | import com.example.security.entity.Permission; 4 | import com.example.security.entity.RolePermission; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | /** 10 | * @Autoor:杨文彬 11 | * @Date:2019/1/22 12 | * @Description: 13 | */ 14 | public interface PermissionMapper { 15 | List getAllMenuTree(); 16 | 17 | List getParentMenu(Long per_parent_id); 18 | 19 | 20 | Integer update(Map map); 21 | 22 | Integer add(Permission permission); 23 | 24 | List getPerIdList(Long rp_role_id); 25 | 26 | Integer addRP(RolePermission rolePermission); 27 | 28 | Integer del(Long rp_role_id); 29 | 30 | Integer getCount(Long rp_role_id); 31 | 32 | Integer delByPerid(Long per_id); 33 | } -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/mapper/RoleMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.security.mapper; 2 | 3 | import com.example.security.entity.Permission; 4 | import com.example.security.entity.Role; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Set; 10 | 11 | /** 12 | * @Autoor:杨文彬 13 | * @Date:2019/1/7 14 | * @Description: 15 | */ 16 | public interface RoleMapper { 17 | 18 | Integer add(Role role); 19 | 20 | Integer del(Long id); 21 | 22 | Integer update(Map map); 23 | 24 | Set selectByUserName(String username); 25 | 26 | ArrayList getRoleListByCond(Map map); 27 | 28 | ArrayList getMenuTree(Map map); 29 | 30 | List getAllRoleList(); 31 | 32 | List getRoleListByPerId(Long rp_per_id); 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.security.mapper; 2 | 3 | import com.example.security.entity.User; 4 | import com.example.security.util.RetResult; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.apache.ibatis.annotations.Mapper; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import java.util.Map; 10 | 11 | /** 12 | * @Autoor:杨文彬 13 | * @Date:2019/1/4 14 | * @Description: 15 | */ 16 | 17 | public interface UserMapper { 18 | 19 | User selectByUserName(String username); 20 | 21 | String selectPasswordByUsername(String username); 22 | 23 | Integer selectUserNameIsExist(String username); 24 | 25 | User selectUserByUsername(String username); 26 | } 27 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/service/PermissionService.java: -------------------------------------------------------------------------------- 1 | package com.example.security.service; 2 | 3 | import com.example.security.entity.Permission; 4 | import com.example.security.util.RetResult; 5 | 6 | import java.util.Map; 7 | 8 | /** 9 | * @Autoor:杨文彬 10 | * @Date:2019/1/22 11 | * @Description: 12 | */ 13 | public interface PermissionService { 14 | RetResult update(Map map); 15 | 16 | RetResult add(Map map); 17 | 18 | RetResult queryAllMenusTree(Map map); 19 | 20 | RetResult getPerIdList(Map map); 21 | 22 | RetResult addRP(Map map); 23 | 24 | RetResult del(Map map); 25 | } 26 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/service/RoleService.java: -------------------------------------------------------------------------------- 1 | package com.example.security.service; 2 | 3 | import com.example.security.entity.Role; 4 | import com.example.security.util.RetResult; 5 | 6 | import java.util.ArrayList; 7 | import java.util.Map; 8 | import java.util.Set; 9 | 10 | /** 11 | * @Autoor:杨文彬 12 | * @Date:2019/1/7 13 | * @Description: 14 | */ 15 | public interface RoleService { 16 | 17 | RetResult getRoleListByCond(Map map); 18 | 19 | RetResult getAllRoleList(Map map); 20 | 21 | RetResult getRoleListByPerId(Map map); 22 | 23 | RetResult addRoleById(Map map); 24 | 25 | RetResult delRoleById(Map map); 26 | 27 | RetResult updateById(Map map); 28 | } 29 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.example.security.service; 2 | 3 | import com.example.security.entity.Permission; 4 | import com.example.security.entity.User; 5 | import com.example.security.jwt.JwtTokenUtil; 6 | import com.example.security.mapper.UserMapper; 7 | import com.example.security.util.RetCode; 8 | import com.example.security.util.RetResult; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.security.authentication.AuthenticationManager; 12 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 13 | import org.springframework.security.core.Authentication; 14 | import org.springframework.security.core.AuthenticationException; 15 | import org.springframework.security.core.context.SecurityContextHolder; 16 | import org.springframework.security.core.userdetails.UserDetails; 17 | import org.springframework.security.core.userdetails.UserDetailsService; 18 | import org.springframework.stereotype.Service; 19 | 20 | import java.util.List; 21 | import java.util.Map; 22 | 23 | /** 24 | * @Author:YangWenbin 25 | * @Description: 26 | * @Date:20:44 2019/1/5 27 | * @ModifiedBy: 28 | */ 29 | 30 | public interface UserService { 31 | 32 | 33 | User findByUsername(String username); 34 | 35 | 36 | RetResult login(String username, String password); 37 | 38 | RetResult getUserInfo(String username); 39 | 40 | /** 41 | * 获取菜单树 42 | * @param username 43 | * @return 44 | */ 45 | RetResult getMenuTree(String username); 46 | 47 | Object getAllMenuTree(List permissionList); 48 | 49 | List getMenuTreeByPid(Long per_parent_id); 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/service/impl/JwtUserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.security.service.impl; 2 | 3 | import com.example.security.entity.Role; 4 | import com.example.security.entity.User; 5 | import com.example.security.jwt.JwtUser; 6 | import com.example.security.mapper.UserMapper; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.security.core.userdetails.UserDetailsService; 12 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 13 | import org.springframework.stereotype.Service; 14 | 15 | import java.util.List; 16 | import java.util.stream.Collectors; 17 | 18 | /** 19 | * @Autoor:杨文彬 20 | * @Date:2019/1/4 21 | * @Description: 22 | */ 23 | @Slf4j 24 | @Service 25 | public class JwtUserDetailsServiceImpl implements UserDetailsService { 26 | 27 | 28 | 29 | @Autowired 30 | private UserMapper userMapper; 31 | @Override 32 | public JwtUser loadUserByUsername(String s) throws UsernameNotFoundException { 33 | 34 | User user = userMapper.selectByUserName(s); 35 | if(user == null){ 36 | throw new UsernameNotFoundException(String.format("'%s'.这个用户不存在", s)); 37 | } 38 | List collect = user.getRoles().stream().map(Role::getRolename).map(SimpleGrantedAuthority::new).collect(Collectors.toList()); 39 | return new JwtUser(user.getId(),user.getUsername(), user.getPassword(), user.getState(), collect); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/service/impl/PermissionServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.security.service.impl; 2 | 3 | import com.example.security.entity.Permission; 4 | import com.example.security.entity.RolePermission; 5 | import com.example.security.mapper.PermissionMapper; 6 | import com.example.security.service.PermissionService; 7 | import com.example.security.util.GenTree; 8 | import com.example.security.util.RetCode; 9 | import com.example.security.util.RetResult; 10 | import com.example.security.util.SnowFlake; 11 | import lombok.extern.slf4j.Slf4j; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.stereotype.Service; 14 | 15 | import java.sql.Timestamp; 16 | import java.time.LocalDateTime; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | import java.util.Map; 20 | 21 | /** 22 | * @Autoor:杨文彬 23 | * @Date:2019/1/22 24 | * @Description: 25 | */ 26 | @Slf4j 27 | @Service 28 | public class PermissionServiceImpl implements PermissionService { 29 | 30 | @Autowired 31 | private PermissionMapper permissionMapper; 32 | 33 | 34 | 35 | 36 | /** 37 | * 更新菜单 38 | * @param map 39 | * @return 40 | */ 41 | @Override 42 | public RetResult update(Map map) { 43 | if(map.get("per_id") == null){ 44 | return new RetResult(RetCode.FAIL.getCode(),"id不能为空"); 45 | } 46 | return new RetResult(RetCode.SUCCESS.getCode(),permissionMapper.update(map)); 47 | } 48 | 49 | /** 50 | * 添加菜单 51 | * @param map 52 | * @return 53 | */ 54 | @Override 55 | public RetResult add(Map map) { 56 | if( map.get("per_resource") ==null){ 57 | return new RetResult(RetCode.FAIL.getCode(),"Id,Url路径不能为空"); 58 | } 59 | Permission permission = new Permission(map); 60 | SnowFlake snowFlake = new SnowFlake(2,3); 61 | permission.setPer_id(snowFlake.nextId()); 62 | log.info(permission.getPer_id().toString()); 63 | permission.setPer_crtTime(Timestamp.valueOf(LocalDateTime.now())); 64 | permission.setPer_type("menu"); 65 | return new RetResult(RetCode.SUCCESS.getCode(),"添加成功",permissionMapper.add(permission)); 66 | } 67 | 68 | 69 | /** 70 | * 获取所有菜单树,树形表格数据 71 | * @param map 72 | * @return 73 | */ 74 | @Override 75 | public RetResult queryAllMenusTree(Map map) { 76 | return new RetResult(RetCode.SUCCESS.getCode(), GenTree.genRoot(permissionMapper.getAllMenuTree())); 77 | } 78 | 79 | @Override 80 | public RetResult getPerIdList(Map map) { 81 | if(map.get("rp_role_id") == null){ 82 | return new RetResult(RetCode.FAIL.getCode(),"id不能为空"); 83 | } 84 | 85 | return new RetResult(RetCode.SUCCESS.getCode(),permissionMapper.getPerIdList(Long.parseLong(map.get("rp_role_id").toString()))); 86 | } 87 | 88 | @Override 89 | public RetResult addRP(Map map) { 90 | if (map.get("rp_role_id") == null) { 91 | return new RetResult(RetCode.FAIL.getCode(), "角色id不能为空"); 92 | } else { 93 | if (permissionMapper.getCount(Long.parseLong(map.get("rp_role_id").toString())) > 0){ 94 | permissionMapper.del(Long.parseLong(map.get("rp_role_id").toString())); 95 | } 96 | List list = (List) map.get("checkIds");; 97 | if(list != null && list.size() > 0){ 98 | List longList = new ArrayList<>(); 99 | for (Object id : list){ 100 | longList.add(Long.valueOf(id.toString())); 101 | } 102 | for (Long ids : longList) { 103 | RolePermission rolePermission = new RolePermission(map); 104 | SnowFlake snowFlake = new SnowFlake(2,3); 105 | rolePermission.setRp_id(snowFlake.nextId()); 106 | rolePermission.setRp_per_id(ids); 107 | permissionMapper.addRP(rolePermission); 108 | } 109 | } 110 | } 111 | 112 | return new RetResult(RetCode.SUCCESS.getCode(), "更新成功"); 113 | } 114 | 115 | @Override 116 | public RetResult del(Map map) { 117 | if(map.get("per_id") == null){ 118 | return new RetResult(RetCode.FAIL.getCode(),"菜单id不能为空"); 119 | } 120 | return new RetResult(RetCode.SUCCESS.getCode(),permissionMapper.delByPerid(Long.parseLong(map.get("per_id").toString()))); 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/service/impl/RoleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.security.service.impl; 2 | 3 | import com.example.security.entity.Role; 4 | import com.example.security.mapper.RoleMapper; 5 | import com.example.security.service.RoleService; 6 | import com.example.security.util.PageUtil; 7 | import com.example.security.util.RetCode; 8 | import com.example.security.util.RetResult; 9 | import com.example.security.util.SnowFlake; 10 | import com.github.pagehelper.Page; 11 | import com.github.pagehelper.PageHelper; 12 | import lombok.extern.slf4j.Slf4j; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.stereotype.Service; 15 | 16 | import java.sql.Timestamp; 17 | import java.time.LocalDateTime; 18 | import java.util.*; 19 | 20 | /** 21 | * @Autoor:杨文彬 22 | * @Date:2019/1/7 23 | * @Description: 24 | */ 25 | @Service 26 | @Slf4j 27 | public class RoleServiceImpl implements RoleService 28 | { 29 | 30 | @Autowired 31 | private RoleMapper roleMapper; 32 | 33 | 34 | /** 35 | * 分页获取角色列表 36 | * @param map 37 | * @return 38 | */ 39 | @Override 40 | public RetResult getRoleListByCond(Map map) { 41 | 42 | Integer pageCur = Integer.valueOf(map.get("curPageNum").toString()); 43 | Integer pageSize = Integer.valueOf(map.get("pageSize").toString()); 44 | 45 | /** 46 | * 分页数据 47 | */ 48 | Page page = PageHelper.startPage(pageCur,pageSize); 49 | ArrayList list = roleMapper.getRoleListByCond(map); 50 | PageUtil pageData = new PageUtil(page,list); 51 | return new RetResult(RetCode.SUCCESS.getCode(),"查询成功",pageData); 52 | } 53 | 54 | /** 55 | * 得到角色列表,资源管理使用 56 | * @param map 57 | * @return 58 | */ 59 | @Override 60 | public RetResult getAllRoleList(Map map) { 61 | List roles = roleMapper.getAllRoleList(); 62 | List> roleList = new ArrayList<>(); 63 | for (Role role :roles ){ 64 | Map map1 = new HashMap<>(); 65 | map1.put("id",role.getId()); 66 | map1.put("label",role.getRolename()); 67 | roleList.add(map1); 68 | } 69 | return new RetResult(RetCode.SUCCESS.getCode(),roleList); 70 | } 71 | 72 | /** 73 | * 通过资源id获取角色集合 74 | * @param map 75 | * @return 76 | */ 77 | @Override 78 | public RetResult getRoleListByPerId(Map map) { 79 | List ids = new ArrayList<>(); 80 | List roleList = roleMapper.getRoleListByPerId(Long.parseLong(map.get("per_id").toString())); 81 | for (Role role : roleList) { 82 | Long id = role.getId(); 83 | ids.add(id); 84 | } 85 | return new RetResult(RetCode.SUCCESS.getCode(),ids); 86 | } 87 | 88 | /** 89 | * 添加角色 90 | * @param map 91 | * @return 92 | */ 93 | @Override 94 | public RetResult addRoleById(Map map) { 95 | Role role = new Role(); 96 | SnowFlake snowFlake = new SnowFlake(2,3); 97 | role.setId(snowFlake.nextId()); 98 | role.setCreateTime(Timestamp.valueOf(LocalDateTime.now())); 99 | role.setRolename((String) map.get("rolename")); 100 | role.setRoledesc((String) map.get("roledesc")); 101 | return new RetResult(RetCode.SUCCESS.getCode(),roleMapper.add(role)); 102 | 103 | } 104 | 105 | /** 106 | * 删除角色 107 | * @param map 108 | * @return 109 | */ 110 | @Override 111 | public RetResult delRoleById(Map map) { 112 | if(map.get("id") == null) { 113 | return new RetResult(RetCode.FAIL.getCode(),"id不能为空"); 114 | } 115 | return new RetResult(RetCode.SUCCESS.getCode(),roleMapper.del(Long.parseLong(map.get("id").toString()))); 116 | } 117 | 118 | /** 119 | * 更新角色信息 120 | * @param map 121 | * @return 122 | */ 123 | @Override 124 | public RetResult updateById(Map map) { 125 | if (map.get("id") == null) { 126 | 127 | return new RetResult(RetCode.FAIL.getCode(),"id不能为空"); 128 | } 129 | return new RetResult(RetCode.SUCCESS.getCode(),roleMapper.update(map)); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.security.service.impl; 2 | 3 | import com.example.security.entity.Permission; 4 | import com.example.security.entity.Role; 5 | import com.example.security.entity.User; 6 | import com.example.security.jwt.JwtTokenUtil; 7 | import com.example.security.jwt.JwtUser; 8 | import com.example.security.mapper.PermissionMapper; 9 | import com.example.security.mapper.RoleMapper; 10 | import com.example.security.mapper.UserMapper; 11 | import com.example.security.service.UserService; 12 | import com.example.security.util.*; 13 | import lombok.extern.slf4j.Slf4j; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.security.authentication.AuthenticationManager; 16 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 17 | import org.springframework.security.core.Authentication; 18 | import org.springframework.security.core.AuthenticationException; 19 | import org.springframework.security.core.context.SecurityContextHolder; 20 | import org.springframework.security.core.userdetails.UserDetails; 21 | import org.springframework.security.core.userdetails.UserDetailsService; 22 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 23 | import org.springframework.security.crypto.password.PasswordEncoder; 24 | import org.springframework.stereotype.Service; 25 | 26 | import javax.annotation.Resource; 27 | import java.util.*; 28 | 29 | /** 30 | * @Author:YangWenbin 31 | * @Description: 32 | * @Date:21:38 2019/1/5 33 | * @ModifiedBy: 34 | */ 35 | @Slf4j 36 | @Service 37 | public class UserServiceImpl implements UserService { 38 | @Autowired 39 | private UserMapper userMapper; 40 | 41 | @Autowired 42 | private RoleMapper roleMapper; 43 | 44 | @Autowired 45 | private PermissionMapper permissionMapper; 46 | 47 | @Resource 48 | private RedisUtil redisUtil; 49 | 50 | 51 | 52 | @Autowired 53 | private AuthenticationManager authenticationManager; 54 | 55 | @Autowired 56 | private UserDetailsService userDetailsService; 57 | 58 | @Autowired 59 | private JwtTokenUtil jwtTokenUtil; 60 | 61 | @Autowired 62 | private PasswordEncoder passwordEncoder; 63 | 64 | /** 65 | * 获取用户信息 66 | * @param username 67 | * @return 68 | */ 69 | @Override 70 | public User findByUsername(String username) { 71 | User user = userMapper.selectByUserName(username); 72 | log.info("userserviceimpl"+user); 73 | return user; 74 | } 75 | 76 | /** 77 | * 登录方法 78 | * @param username 79 | * @param passwordAES 80 | * @return 81 | * @throws AuthenticationException 82 | */ 83 | @Override 84 | public RetResult login(String username, String passwordAES) throws AuthenticationException { 85 | BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); 86 | String password = null; 87 | password = AesEncryptUtil.decrypt(passwordAES); 88 | if (username == null || passwordAES == null) { 89 | return new RetResult(RetCode.FAIL.getCode(),"用户名,密码不能为空"); 90 | } 91 | if (! (userMapper.selectUserNameIsExist(username) > 0)){ 92 | return new RetResult(RetCode.FAIL.getCode(),"用户名不存在,请重试"); 93 | }else if(!encoder.matches(password,userMapper.selectPasswordByUsername(username))) { 94 | return new RetResult(RetCode.FAIL.getCode(), "密码输入不正确,请重试"); 95 | } 96 | UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password); 97 | final Authentication authentication = authenticationManager.authenticate(upToken); 98 | SecurityContextHolder.getContext().setAuthentication(authentication); 99 | JwtUser userDetails = (JwtUser)userDetailsService.loadUserByUsername(username); 100 | long refreshPeriodTime = 240L; 101 | String jwt = jwtTokenUtil.generateToken(userDetails); 102 | String userId = userMapper.selectUserByUsername(username).getId(); 103 | //把签发的jwt token存储到redis中,时间根绝你免登录的时间来设置 104 | redisUtil.setAndTime(userId,jwt,refreshPeriodTime); 105 | return new RetResult(RetCode.SUCCESS.getCode(),"登录成功",jwt); 106 | } 107 | 108 | /** 109 | * 获取用户信息,包括角色列表,权限资源,返回给前端使用 110 | * @param username 111 | * @return 112 | */ 113 | @Override 114 | public RetResult getUserInfo(String username) { 115 | User user = userMapper.selectByUserName(username); 116 | //查询出改用户下的角色和权限 117 | Set roles = roleMapper.selectByUserName(username); 118 | List permissions = new LinkedList(); 119 | Set menus = new HashSet<>(); 120 | roles.forEach( role -> { 121 | role.getPermissions().forEach( permission -> { 122 | if(permission.getPer_type().equals("menu")){ 123 | permissions.add(new Permission(permission.getPer_id(),permission.getPer_parent_id(),permission.getPer_name(), 124 | permission.getPer_resource(),permission.getPer_type(),permission.getPer_icon(),permission.getPer_describe(), 125 | permission.getPer_component(),permission.getPer_sort(),permission.getPer_crtTime(), permission.getChildren())); 126 | } 127 | }); 128 | }); 129 | UserVo userVo =new UserVo(user.getId(),user.getUsername(),user.getRoles(), BulidTree.genRoot(GenTree.genRoot(permissions))); 130 | return new RetResult(RetCode.SUCCESS.getCode(),userVo); 131 | 132 | } 133 | 134 | /** 135 | * 获取菜单树 136 | * @param username 137 | * @return 138 | */ 139 | @Override 140 | public RetResult getMenuTree(String username) { 141 | List permissions = new ArrayList(); 142 | Set roles = roleMapper.selectByUserName(username); 143 | roles.forEach( role -> { 144 | role.getPermissions().forEach( permission -> { 145 | if(permission.getPer_type().equals("menu")){ 146 | permissions.add(new Permission(permission.getPer_id(),permission.getPer_parent_id(),permission.getPer_name(), 147 | permission.getPer_resource(),permission.getPer_type(),permission.getPer_icon(),permission.getPer_describe(), 148 | permission.getPer_component(),permission.getPer_sort(),permission.getPer_crtTime(), permission.getChildren())); 149 | } 150 | }); 151 | }); 152 | 153 | return new RetResult(RetCode.SUCCESS.getCode(),"获取菜单树成功",GenTree.genRoot(permissions)); 154 | } 155 | 156 | /** 157 | * 获取所有的菜单树树形表格用 158 | * @param permissionList 159 | * @return 160 | */ 161 | public Object getAllMenuTree(List permissionList){ 162 | List> permissions = new ArrayList<>(); 163 | permissionList.forEach( permission -> { 164 | if(permission != null) { 165 | List permissionList1 = permissionMapper.getParentMenu(permission.getPer_id()); 166 | //vue treeselect 需要的是{"id":"*","label":"*"}格式 167 | Map map1 = new HashMap<>(); 168 | map1.put("id",permission.getPer_id()); 169 | map1.put("label",permission.getPer_name()); 170 | if( permissionList1 != null && permissionList1.size() > 0){ 171 | map1.put("children",getAllMenuTree(permissionList1)); 172 | } 173 | permissions.add(map1); 174 | } 175 | }); 176 | return permissions; 177 | } 178 | 179 | /** 180 | * 通过菜单id获取菜单树 181 | * @param per_parent_id 182 | * @return 183 | */ 184 | @Override 185 | public List getMenuTreeByPid(Long per_parent_id) { 186 | return permissionMapper.getParentMenu(per_parent_id); 187 | } 188 | 189 | 190 | } 191 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/util/AesEncryptUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.security.util; 2 | 3 | 4 | import org.apache.commons.codec.binary.Base64; 5 | 6 | import javax.crypto.*; 7 | import javax.crypto.spec.IvParameterSpec; 8 | import javax.crypto.spec.SecretKeySpec; 9 | import java.io.UnsupportedEncodingException; 10 | import java.nio.charset.Charset; 11 | import java.security.InvalidAlgorithmParameterException; 12 | import java.security.InvalidKeyException; 13 | import java.security.NoSuchAlgorithmException; 14 | 15 | /** 16 | * @Autoor:杨文彬 17 | * @Date:2019/2/1 18 | * @Description:解密前端传递过来的加密密码 19 | */ 20 | public class AesEncryptUtil { 21 | 22 | private static String iv = "0123456789ABCDEF";//偏移量字符串必须是16位 当模式是CBC的时候必须设置偏移量 23 | private static String Algorithm = "AES"; 24 | private static String AlgorithmProvider = "AES/CBC/PKCS5Padding"; //算法/模式/补码方式 25 | 26 | public static byte[] generatorKey() throws NoSuchAlgorithmException { 27 | KeyGenerator keyGenerator = KeyGenerator.getInstance(Algorithm); 28 | keyGenerator.init(256);//默认128,获得无政策权限后可为192或256 29 | SecretKey secretKey = keyGenerator.generateKey(); 30 | return secretKey.getEncoded(); 31 | } 32 | 33 | public static IvParameterSpec getIv() throws UnsupportedEncodingException { 34 | IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8")); 35 | return ivParameterSpec; 36 | } 37 | 38 | /** 39 | * 加密 40 | * @param src 41 | * @param key 42 | * @return 43 | * @throws NoSuchAlgorithmException 44 | * @throws NoSuchPaddingException 45 | * @throws InvalidKeyException 46 | * @throws IllegalBlockSizeException 47 | * @throws BadPaddingException 48 | * @throws UnsupportedEncodingException 49 | * @throws InvalidAlgorithmParameterException 50 | */ 51 | public static byte[] encrypt(String src, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, 52 | InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException { 53 | SecretKey secretKey = new SecretKeySpec(key, Algorithm); 54 | IvParameterSpec ivParameterSpec = getIv(); 55 | Cipher cipher = Cipher.getInstance(AlgorithmProvider); 56 | cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec); 57 | byte[] cipherBytes = cipher.doFinal(src.getBytes(Charset.forName("utf-8"))); 58 | return cipherBytes; 59 | } 60 | 61 | /** 62 | * 解密 63 | * @param src 原密码 64 | * @param key 解密后的byte数组 65 | * @return 66 | * @throws Exception 67 | */ 68 | public static byte[] decrypt(String src, byte[] key) throws Exception { 69 | SecretKey secretKey = new SecretKeySpec(key, Algorithm); 70 | 71 | IvParameterSpec ivParameterSpec = getIv(); 72 | Cipher cipher = Cipher.getInstance(AlgorithmProvider); 73 | cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec); 74 | byte[] hexBytes = hexStringToBytes(src); 75 | byte[] plainBytes = cipher.doFinal(hexBytes); 76 | return plainBytes; 77 | } 78 | 79 | /** 80 | * 将byte转换为16进制字符串 81 | * @param src 82 | * @return 83 | */ 84 | public static String byteToHexString(byte[] src) { 85 | StringBuilder sb = new StringBuilder(); 86 | for (int i = 0; i < src.length; i++) { 87 | int v = src[i] & 0xff; 88 | String hv = Integer.toHexString(v); 89 | if (hv.length() < 2) { 90 | sb.append("0"); 91 | } 92 | sb.append(hv); 93 | } 94 | return sb.toString(); 95 | } 96 | 97 | /** 98 | * 将16进制字符串装换为byte数组 99 | * @param hexString 100 | * @return 101 | */ 102 | public static byte[] hexStringToBytes(String hexString) { 103 | hexString = hexString.toUpperCase(); 104 | int length = hexString.length() / 2; 105 | char[] hexChars = hexString.toCharArray(); 106 | byte[] b = new byte[length]; 107 | for (int i = 0; i < length; i++) { 108 | int pos = i * 2; 109 | b[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); 110 | } 111 | return b; 112 | } 113 | 114 | private static byte charToByte(char c) { 115 | return (byte) "0123456789ABCDEF".indexOf(c); 116 | } 117 | 118 | /** 119 | * 直接传入psd然后解码进行验证使用 120 | * @param psd 前台传过来的String 加密后的数组 121 | * @return 122 | */ 123 | public static String decrypt(String psd) { 124 | try { 125 | byte key[] = "1234567890ABCDEF1234567890ABCDEf".getBytes("utf-8"); 126 | return new String(decrypt(psd, key)); 127 | } catch (Exception e) { 128 | e.printStackTrace(); 129 | return null; 130 | } 131 | 132 | 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/util/BulidTree.java: -------------------------------------------------------------------------------- 1 | package com.example.security.util; 2 | 3 | import com.example.security.entity.Permission; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.apache.commons.lang3.StringUtils; 6 | 7 | import java.util.*; 8 | 9 | 10 | /** 11 | * @Autoor:杨文彬 12 | * @Date:2019/1/18 13 | * @Description:设置给前台用的路由菜单 14 | */ 15 | @Slf4j 16 | public class BulidTree { 17 | 18 | public static List genRoot(List permissions){ 19 | 20 | List trees = new LinkedList(); 21 | permissions.forEach(permission -> { 22 | if(permission != null){ 23 | List permissionList = permission.getChildren(); 24 | Menu menu = new Menu(); 25 | menu.setName(permission.getPer_name()); 26 | menu.setPath(permission.getPer_resource()); 27 | if(permission.getPer_parent_id().toString().equals("0")){ 28 | //一级菜单的path需要加'/' 29 | menu.setPath("/"+permission.getPer_resource()); 30 | //判断component是否为空如果是空返回Layout给前端 31 | menu.setComponent(StringUtils.isEmpty(permission.getPer_component()) ?"Layout" : permission.getPer_component()); 32 | }else{ 33 | menu.setComponent(permission.getPer_component()); 34 | } 35 | menu.setMeta(new MenuMetaVo(permission.getPer_name(),permission.getPer_icon())); 36 | //判断是否有子路由 37 | if(permissionList != null && permissionList.size() != 0){ 38 | menu.setAlwaysShow(true); 39 | menu.setRedirect("noredirect"); 40 | menu.setChildren(genRoot(permissionList)); 41 | } else if (permission.getPer_parent_id().toString().equals("0")){ 42 | Menu menu1 = new Menu(); 43 | menu1.setMeta(menu.getMeta()); 44 | menu1.setPath("index"); 45 | menu1.setName(menu.getName()); 46 | menu1.setComponent(menu.getComponent()); 47 | menu.setName(null); 48 | menu.setMeta(null); 49 | menu.setComponent("Layout"); 50 | List menuList = new ArrayList(); 51 | menuList.add(menu1); 52 | menu.setChildren(menuList); 53 | } 54 | trees.add(menu); 55 | 56 | } 57 | 58 | }); 59 | return trees; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/util/GenTree.java: -------------------------------------------------------------------------------- 1 | package com.example.security.util; 2 | 3 | import com.example.security.entity.Permission; 4 | 5 | import java.util.*; 6 | 7 | /** 8 | * @Autoor:杨文彬 9 | * @Date:2019/1/7 10 | * @Description:把数据库中的list转成树形结构 11 | */ 12 | public class GenTree { 13 | 14 | 15 | /** 16 | * 递归根节点 17 | * @param nodes 18 | * @return 19 | */ 20 | public static List genRoot(List nodes){ 21 | List root = new LinkedList(); 22 | //遍历数据 23 | nodes.forEach(permission -> { 24 | //当父id是0的时候应该是根节点 25 | if(permission.getPer_parent_id() == 0){ 26 | root.add(permission); 27 | } 28 | }); 29 | //这里是子节点的创建方法 30 | root.forEach(permission -> { 31 | genChildren(permission,nodes); 32 | }); 33 | //返回数据 34 | return root; 35 | } 36 | 37 | /** 38 | * 递归子节点 39 | * @param permission 40 | * @param nodes 41 | * @return 42 | */ 43 | private static Permission genChildren(Permission permission, List nodes) { 44 | //遍历传过来的数据 45 | for (Permission permission1 :nodes){ 46 | //如果数据中的父id和上面的per_id一致应该就放children中去 47 | if(permission.getPer_id().equals(permission1.getPer_parent_id())){ 48 | //如果当前节点的子节点是空的则初始化,如果不为空就加进去 49 | if(permission.getChildren() == null){ 50 | permission.setChildren(new LinkedList<>()); 51 | } 52 | permission.getChildren().add(genChildren(permission1,nodes)); 53 | } 54 | } 55 | //返回数据 56 | return permission; 57 | } 58 | 59 | 60 | } 61 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/util/Menu.java: -------------------------------------------------------------------------------- 1 | package com.example.security.util; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * @Autoor:杨文彬 9 | * @Date:2019/1/7 10 | * @Description:菜单类,这个是为了生成权限菜单树形结构 11 | */ 12 | @Data 13 | public class Menu { 14 | private String name; 15 | private String path; 16 | private String component; 17 | private String redirect; 18 | private MenuMetaVo meta; 19 | private List children; 20 | private Boolean alwaysShow; 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/util/MenuMetaVo.java: -------------------------------------------------------------------------------- 1 | package com.example.security.util; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @Autoor:杨文彬 7 | * @Date:2019/1/18 8 | * @Description: 9 | */ 10 | @Data 11 | public class MenuMetaVo { 12 | private String title; 13 | 14 | private String icon; 15 | 16 | public MenuMetaVo(String title, String icon) { 17 | this.title = title; 18 | this.icon = icon; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/util/PageUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.security.util; 2 | 3 | import com.github.pagehelper.Page; 4 | import lombok.Data; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * @Autoor:杨文彬 10 | * @Date:2019/1/21 11 | * @Description: 12 | */ 13 | @Data 14 | public class PageUtil { 15 | private Integer pageCur; 16 | private Integer pageSize; 17 | private Integer rowTotal; 18 | private Integer pageTotal; 19 | private List data; 20 | 21 | public PageUtil(Page page,List data) { 22 | this.pageCur = page.getPageNum(); 23 | this.pageSize = page.getPageSize(); 24 | this.rowTotal = page.getPages(); 25 | this.pageTotal = Integer.valueOf((int)page.getTotal()); 26 | this.data = data; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/util/RedisUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.security.util; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.data.redis.core.RedisTemplate; 5 | import org.springframework.data.redis.core.ValueOperations; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.io.Serializable; 9 | import java.util.concurrent.TimeUnit; 10 | 11 | /** 12 | * @Autoor:杨文彬 13 | * @Date:2019/2/21 14 | * @Description: 15 | */ 16 | @Component 17 | public class RedisUtil { 18 | @Autowired 19 | private RedisTemplate redisTemplate; 20 | 21 | /** 22 | * 存键值对 23 | * @param key 24 | * @param value 25 | */ 26 | public void set(String key,String value){ 27 | ValueOperations valueOperations = redisTemplate.opsForValue(); 28 | valueOperations.set(key,value); 29 | } 30 | 31 | public long getExpireTime(String key){ 32 | long time = redisTemplate.getExpire(key); 33 | return time; 34 | } 35 | 36 | /** 37 | * 存储键值对,并且设置有效期 38 | * @param key 39 | * @param value 40 | * @param time 41 | */ 42 | public void setAndTime(String key,String value,long time){ 43 | ValueOperations valueOperations = redisTemplate.opsForValue(); 44 | valueOperations.set(key,value); 45 | redisTemplate.expire(key,time,TimeUnit.SECONDS); 46 | } 47 | 48 | 49 | 50 | /** 51 | * 读取redis 52 | * @param key 53 | * @return 54 | */ 55 | public String get( String key) { 56 | Object result = null; 57 | ValueOperations operations = redisTemplate.opsForValue(); 58 | result = operations.get(key); 59 | return (String)result; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/util/RetCode.java: -------------------------------------------------------------------------------- 1 | package com.example.security.util; 2 | 3 | /** 4 | * @Autoor:杨文彬 5 | * @Date:2019/1/4 6 | * @Description: 7 | */ 8 | public enum RetCode { 9 | 10 | //成功 11 | SUCCESS(200), 12 | 13 | //失败 14 | FAIL(400), 15 | 16 | //错误 17 | FALSE(404), 18 | 19 | //token过期 20 | EXPIRED(401), 21 | 22 | //无权限 23 | NODEFINED(403), 24 | 25 | //内部错误 26 | ERROR(500); 27 | 28 | private int code; 29 | 30 | private RetCode(Integer code){ 31 | this.code = code; 32 | } 33 | 34 | public int getCode() { 35 | return code; 36 | } 37 | 38 | public void setCode(int code) { 39 | this.code = code; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/util/RetResult.java: -------------------------------------------------------------------------------- 1 | package com.example.security.util; 2 | 3 | /** 4 | * @Autoor:杨文彬 5 | * @Date:2019/1/4 6 | * @Description: 7 | */ 8 | public class RetResult { 9 | 10 | private Integer code; 11 | private String msg; 12 | private Object data; 13 | 14 | public RetResult(){ 15 | this.code = Integer.valueOf(0); 16 | this.msg = ""; 17 | this.data = null; 18 | } 19 | /** 20 | *返回状态码、信息、以及数据 21 | */ 22 | public RetResult(Integer code, String msg, Object data) { 23 | this.code = code; 24 | this.msg = msg; 25 | this.data = data; 26 | } 27 | /** 28 | *只返回状态码,以及信息可以用于失败时候来使用 29 | */ 30 | public RetResult(Integer code, String msg) { 31 | this.code = code; 32 | this.msg = msg; 33 | this.data = null; 34 | } 35 | /** 36 | *只返回状态码和数据 37 | */ 38 | public RetResult(Integer code, Object data) { 39 | this.code = code; 40 | this.msg = ""; 41 | this.data = data; 42 | } 43 | 44 | public Integer getCode() { 45 | return code; 46 | } 47 | 48 | public void setCode(Integer code) { 49 | this.code = code; 50 | } 51 | 52 | public String getMsg() { 53 | return msg; 54 | } 55 | 56 | public void setMsg(String msg) { 57 | this.msg = msg; 58 | } 59 | 60 | public Object getData() { 61 | return data; 62 | } 63 | 64 | public void setData(Object data) { 65 | this.data = data; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/util/SnowFlake.java: -------------------------------------------------------------------------------- 1 | package com.example.security.util; 2 | 3 | import org.springframework.stereotype.Component; 4 | import org.springframework.stereotype.Service; 5 | 6 | /** 7 | * @Autoor:杨文彬 8 | * @Date:2019/1/24 9 | * @Description: 10 | */ 11 | public class SnowFlake { 12 | /** 13 | * 起始的时间戳 14 | */ 15 | private final static long START_STMP = 1480166465631L; 16 | 17 | /** 18 | * 每一部分占用的位数 19 | */ 20 | private final static long SEQUENCE_BIT = 12; //序列号占用的位数 21 | private final static long MACHINE_BIT = 5; //机器标识占用的位数 22 | private final static long DATACENTER_BIT = 5;//数据中心占用的位数 23 | 24 | /** 25 | * 每一部分的最大值 26 | */ 27 | private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT); 28 | private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT); 29 | private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT); 30 | 31 | /** 32 | * 每一部分向左的位移 33 | */ 34 | private final static long MACHINE_LEFT = SEQUENCE_BIT; 35 | private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT; 36 | private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT; 37 | 38 | private long datacenterId; //数据中心 39 | private long machineId; //机器标识 40 | private long sequence = 0L; //序列号 41 | private long lastStmp = -1L;//上一次时间戳 42 | 43 | public SnowFlake(long datacenterId, long machineId) { 44 | if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) { 45 | throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0"); 46 | } 47 | if (machineId > MAX_MACHINE_NUM || machineId < 0) { 48 | throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0"); 49 | } 50 | this.datacenterId = datacenterId; 51 | this.machineId = machineId; 52 | } 53 | 54 | /** 55 | * 产生下一个ID 56 | * 57 | * @return 58 | */ 59 | public synchronized long nextId() { 60 | long currStmp = getNewstmp(); 61 | if (currStmp < lastStmp) { 62 | throw new RuntimeException("Clock moved backwards. Refusing to generate id"); 63 | } 64 | 65 | if (currStmp == lastStmp) { 66 | //相同毫秒内,序列号自增 67 | sequence = (sequence + 1) & MAX_SEQUENCE; 68 | //同一毫秒的序列数已经达到最大 69 | if (sequence == 0L) { 70 | currStmp = getNextMill(); 71 | } 72 | } else { 73 | //不同毫秒内,序列号置为0 74 | sequence = 0L; 75 | } 76 | 77 | lastStmp = currStmp; 78 | 79 | return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分 80 | | datacenterId << DATACENTER_LEFT //数据中心部分 81 | | machineId << MACHINE_LEFT //机器标识部分 82 | | sequence; //序列号部分 83 | } 84 | 85 | private long getNextMill() { 86 | long mill = getNewstmp(); 87 | while (mill <= lastStmp) { 88 | mill = getNewstmp(); 89 | } 90 | return mill; 91 | } 92 | 93 | private long getNewstmp() { 94 | return System.currentTimeMillis(); 95 | } 96 | 97 | 98 | } 99 | -------------------------------------------------------------------------------- /security/src/main/java/com/example/security/util/UserVo.java: -------------------------------------------------------------------------------- 1 | package com.example.security.util; 2 | 3 | import com.example.security.entity.Role; 4 | import com.example.security.entity.User; 5 | import lombok.Data; 6 | 7 | import java.util.List; 8 | import java.util.Set; 9 | 10 | /** 11 | * @Autoor:杨文彬 12 | * @Date:2019/1/8 13 | * @Description:这个是在User类的基础上添加需要给前端返回用户的角色权限资源列表 14 | */ 15 | @Data 16 | public class UserVo { 17 | 18 | private String id; 19 | 20 | 21 | private String username; 22 | 23 | 24 | 25 | //角色列表(用户和角色是多对多的关系) 26 | 27 | private Set roles; 28 | 29 | //菜单列表 30 | private List menus; 31 | 32 | public UserVo(String id, String username, Set roles, List menus) { 33 | this.id = id; 34 | this.username = username; 35 | this.roles = roles; 36 | this.menus = menus; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /security/src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | driver-class-name: com.mysql.cj.jdbc.Driver 4 | url: 5 | username: 6 | password: 7 | redis: 8 | #数据库索引 9 | database: 4 10 | host: 11 | port: 12 | password: 13 | jedis: 14 | pool: 15 | #最大连接数 16 | max-active: 100 17 | #最大阻塞等待时间(负数表示没限制) 18 | max-wait: 2000 19 | #最大空闲 20 | max-idle: 500 21 | #最小空闲 22 | min-idle: 8 23 | #连接超时时间 24 | timeout: 5000 25 | 26 | logging: 27 | level: 28 | com: 29 | example: 30 | security: 31 | mapper: debug 32 | config: classpath:logback.xml 33 | -------------------------------------------------------------------------------- /security/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | active: dev 4 | datasource: 5 | type: com.alibaba.druid.pool.DruidDataSource 6 | #连接池配置 7 | initialSize: 5 8 | minIdle: 5 9 | maxActive: 20 10 | # 配置获取连接等待超时的时间 11 | maxWait: 60000 12 | timeBetweenEvictionRunsMillis: 6000 13 | # 配置一个连接在池中最小生存的时间,单位是毫秒 14 | minEvictableIdleTimeMillis: 300000 15 | validationQuery: SELECT 1 FROM DUAL 16 | testWhileIdle: true 17 | testOnBorrow: false 18 | testOnReturn: false 19 | # 打开PSCache,并且指定每个连接上PSCache的大小 20 | poolPreparedStatements: true 21 | maxPoolPreparedStatementPerConnectionSize: 20 22 | # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙,此处是filter修改的地方 23 | filters: stat,wall,logback 24 | # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 25 | connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 26 | # 合并多个DruidDataSource的监控数据 27 | useGlobalDataSourceStat: true 28 | 29 | 30 | 31 | 32 | jwt: 33 | header: jwtHeader 34 | secret: eyJleHAiOjE1NDMyMDUyODUsInN1YiI6ImFkbWluIiwiY3JlYXRlZCI6MTU0MDYxMzI4N 35 | expiration: 120000 #毫秒 36 | route: 37 | login: /auth/login 38 | refresh: /auth/refresh 39 | register: /auth/register 40 | #mybatis配置 41 | mybatis: 42 | mapper-locations: classpath*:mapper/**/*Mapper.xml 43 | type-aliases-package: com.example.security.entity 44 | server: 45 | port: 8086 46 | 47 | pagehelper: 48 | helperDialect: mysql 49 | reasonable: true 50 | supportMethodsArguments: true 51 | params: count=countSql 52 | -------------------------------------------------------------------------------- /security/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n 6 | 7 | 8 | 9 | 10 | 11 | 12 | ${user.dir}/logs/log/online-study.%d.log 13 | 14 | 15 | 【xkcoding】%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n 16 | 17 | 18 | 19 | 20 | ERROR 21 | ACCEPT 22 | DENY 23 | 24 | 25 | 26 | 27 | ${user.dir}/logs/error/online-study.%d.error 28 | 29 | 30 | 【xkcoding】%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /security/src/main/resources/mapper/user/PermissionMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | insert into Permission (per_id,per_name,per_parent_id,per_resource,per_type,per_icon,per_describe,per_component,per_sort,per_crtTime) 7 | values(#{per_id},#{per_name},#{per_parent_id},#{per_resource},#{per_type},#{per_icon},#{per_describe},#{per_component},#{per_sort},#{per_crtTime}) 8 | 9 | 10 | 11 | 12 | update Permission 13 | 14 | per_name=#{per_name}, 15 | per_resource=#{per_resource}, 16 | per_type=#{per_type}, 17 | per_icon=#{per_icon}, 18 | per_describe=#{per_describe}, 19 | per_component=#{per_component}, 20 | per_sort=#{per_sort}, 21 | per_crtTime=#{per_crtTime}, 22 | 23 | where per_id=#{per_id} 24 | 25 | 26 | 27 | delete from RolePermission where rp_role_id = #{rp_role_id} 28 | 29 | 30 | 31 | delete from Permission where per_id = #{per_id} 32 | 33 | 34 | 37 | 38 | 41 | 42 | 43 | insert into RolePermission (rp_id,rp_role_id,rp_per_id) value (#{rp_id},#{rp_role_id},#{rp_per_id}) 44 | 45 | 46 | 47 | 48 | 51 | 52 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /security/src/main/resources/mapper/user/RoleMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 37 | 38 | 44 | 45 | 48 | 49 | 53 | 54 | 55 | insert into Role (id,rolename,roledesc,createTime) values (#{id},#{rolename},#{roledesc},#{createTime}) 56 | 57 | 58 | 59 | delete from Role where id = #{id} 60 | 61 | 62 | 63 | update Role 64 | 65 | rolename=#{rolename}, 66 | roledesc=#{roledesc}, 67 | createTime=#{createTime}, 68 | 69 | where id=#{id} 70 | 71 | 72 | -------------------------------------------------------------------------------- /security/src/main/resources/mapper/user/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 22 | 23 | 26 | 27 | 30 | 31 | 34 | -------------------------------------------------------------------------------- /security/src/test/java/com/example/security/SecurityApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.security; 2 | 3 | import com.example.security.mapper.UserMapper; 4 | import com.example.security.util.AesEncryptUtil; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | @RunWith(SpringRunner.class) 13 | @SpringBootTest 14 | public class SecurityApplicationTests { 15 | 16 | 17 | @Test 18 | public void contextLoads() { 19 | 20 | } 21 | 22 | } 23 | 24 | --------------------------------------------------------------------------------