├── .mvn └── wrapper │ ├── maven-wrapper.jar │ ├── maven-wrapper.properties │ └── MavenWrapperDownloader.java ├── src ├── test │ └── java │ │ └── com │ │ └── spring │ │ └── security │ │ ├── SecurityApplicationTests.java │ │ └── Test.java └── main │ ├── java │ └── com │ │ └── spring │ │ └── security │ │ ├── test │ │ └── Test.java │ │ ├── exception │ │ └── NotLoginException.java │ │ ├── SecurityApplication.java │ │ ├── common │ │ ├── utils │ │ │ └── ResultTool.java │ │ ├── enums │ │ │ └── ResultCode.java │ │ └── entity │ │ │ └── JsonResult.java │ │ ├── entity │ │ ├── SysRequestPath.java │ │ ├── SysRequestPathPermissionRelation.java │ │ ├── SysPermission.java │ │ └── SysUser.java │ │ ├── controller │ │ └── UserController.java │ │ ├── service │ │ ├── SysRequestPathService.java │ │ ├── SysUserService.java │ │ ├── SysRequestPathPermissionRelationService.java │ │ ├── SysPermissionService.java │ │ └── impl │ │ │ ├── SysUserServiceImpl.java │ │ │ ├── SysRequestPathServiceImpl.java │ │ │ ├── SysPermissionServiceImpl.java │ │ │ └── SysRequestPathPermissionRelationServiceImpl.java │ │ ├── config │ │ ├── handler │ │ │ ├── CustomizeLogoutSuccessHandler.java │ │ │ ├── CustomizeAuthenticationEntryPoint.java │ │ │ ├── CustomizeAccessDeniedHandler.java │ │ │ ├── CustomizeSessionInformationExpiredStrategy.java │ │ │ ├── CustomizeAccessDecisionManager.java │ │ │ ├── CustomizeFilterInvocationSecurityMetadataSource.java │ │ │ ├── CustomizeAuthenticationSuccessHandler.java │ │ │ ├── CustomizeAbstractSecurityInterceptor.java │ │ │ └── CustomizeAuthenticationFailureHandler.java │ │ ├── service │ │ │ └── UserDetailsServiceImpl.java │ │ └── WebSecurityConfig.java │ │ └── dao │ │ ├── SysRequestPathDao.java │ │ ├── SysUserDao.java │ │ ├── SysRequestPathPermissionRelationDao.java │ │ └── SysPermissionDao.java │ └── resources │ ├── application.yml │ └── mapper │ ├── SysRequestPathDao.xml │ ├── SysRequestPathPermissionRelationDao.xml │ ├── SysPermissionDao.xml │ └── SysUserDao.xml ├── .gitignore ├── pom.xml ├── mvnw.cmd └── mvnw /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/18061495586/Spring-Security-Demo/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip 2 | -------------------------------------------------------------------------------- /src/test/java/com/spring/security/SecurityApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.spring.security; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SecurityApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /src/test/java/com/spring/security/Test.java: -------------------------------------------------------------------------------- 1 | package com.spring.security; 2 | 3 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 4 | 5 | /** 6 | * @Author: Hutengfei 7 | * @Description: 8 | * @Date Create in 2019/9/3 15:17 9 | */ 10 | public class Test { 11 | public static void main(String[] args) { 12 | BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); 13 | System.out.println(encoder.encode("123456")); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/test/Test.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.test; 2 | 3 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 4 | 5 | /** 6 | * @Author: Hutengfei 7 | * @Description: 8 | * @Date Create in 2019/9/5 0:16 9 | */ 10 | public class Test { 11 | public static void main(String[] args) { 12 | BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); 13 | System.out.println(passwordEncoder.encode("123456")); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/exception/NotLoginException.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.exception; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | 5 | /** 6 | * @Author: Hutengfei 7 | * @Description: 8 | * @Date Create in 2019/9/3 20:50 9 | */ 10 | public class NotLoginException extends AuthenticationException { 11 | 12 | public NotLoginException(String msg, Throwable t) { 13 | super(msg, t); 14 | } 15 | 16 | public NotLoginException(String msg) { 17 | super(msg); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/SecurityApplication.java: -------------------------------------------------------------------------------- 1 | package com.spring.security; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 8 | @MapperScan("com.spring.security.dao") 9 | @SpringBootApplication 10 | public class SecurityApplication { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(SecurityApplication.class, args); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/common/utils/ResultTool.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.common.utils; 2 | 3 | 4 | import com.spring.security.common.entity.JsonResult; 5 | import com.spring.security.common.enums.ResultCode; 6 | 7 | /** 8 | * @Author: Hutengfei 9 | * @Description: 10 | * @Date Create in 2019/7/22 19:52 11 | */ 12 | public class ResultTool { 13 | public static JsonResult success() { 14 | return new JsonResult(true); 15 | } 16 | 17 | public static JsonResult success(T data) { 18 | return new JsonResult(true, data); 19 | } 20 | 21 | public static JsonResult fail() { 22 | return new JsonResult(false); 23 | } 24 | 25 | public static JsonResult fail(ResultCode resultEnum) { 26 | return new JsonResult(false, resultEnum); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/entity/SysRequestPath.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * 请求路径(SysRequestPath)实体类 7 | * 8 | * @author makejava 9 | * @since 2019-09-04 17:11:16 10 | */ 11 | public class SysRequestPath implements Serializable { 12 | private static final long serialVersionUID = -38398465698914714L; 13 | //主键id 14 | private Integer id; 15 | //请求路径 16 | private String url; 17 | //路径描述 18 | private String description; 19 | 20 | 21 | public Integer getId() { 22 | return id; 23 | } 24 | 25 | public void setId(Integer id) { 26 | this.id = id; 27 | } 28 | 29 | public String getUrl() { 30 | return url; 31 | } 32 | 33 | public void setUrl(String url) { 34 | this.url = url; 35 | } 36 | 37 | public String getDescription() { 38 | return description; 39 | } 40 | 41 | public void setDescription(String description) { 42 | this.description = description; 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.controller; 2 | 3 | import com.spring.security.common.entity.JsonResult; 4 | import com.spring.security.common.utils.ResultTool; 5 | import com.spring.security.entity.SysUser; 6 | import com.spring.security.service.SysUserService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * @Author: Hutengfei 15 | * @Description: 16 | * @Date Create in 2019/8/28 19:34 17 | */ 18 | @RestController 19 | public class UserController { 20 | @Autowired 21 | SysUserService sysUserService; 22 | 23 | @GetMapping("/getUser") 24 | public JsonResult getUser() { 25 | List users = sysUserService.queryAllByLimit(1, 100); 26 | return ResultTool.success(users); 27 | } 28 | @GetMapping("/test") 29 | public JsonResult test() { 30 | return ResultTool.success("hello world"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/entity/SysRequestPathPermissionRelation.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * 路径权限关联表(SysRequestPathPermissionRelation)实体类 7 | * 8 | * @author makejava 9 | * @since 2019-09-04 17:11:53 10 | */ 11 | public class SysRequestPathPermissionRelation implements Serializable { 12 | private static final long serialVersionUID = -59197738311147860L; 13 | //主键id 14 | private Integer id; 15 | //请求路径id 16 | private Integer urlId; 17 | //权限id 18 | private Integer permissionId; 19 | 20 | 21 | public Integer getId() { 22 | return id; 23 | } 24 | 25 | public void setId(Integer id) { 26 | this.id = id; 27 | } 28 | 29 | public Integer getUrlId() { 30 | return urlId; 31 | } 32 | 33 | public void setUrlId(Integer urlId) { 34 | this.urlId = urlId; 35 | } 36 | 37 | public Integer getPermissionId() { 38 | return permissionId; 39 | } 40 | 41 | public void setPermissionId(Integer permissionId) { 42 | this.permissionId = permissionId; 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/entity/SysPermission.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * 权限表(SysPermission)实体类 7 | * 8 | * @author makejava 9 | * @since 2019-08-29 21:13:29 10 | */ 11 | public class SysPermission implements Serializable { 12 | private static final long serialVersionUID = -71969734644822184L; 13 | //主键id 14 | private Integer id; 15 | //权限code 16 | private String permissionCode; 17 | //权限名 18 | private String permissionName; 19 | 20 | 21 | public Integer getId() { 22 | return id; 23 | } 24 | 25 | public void setId(Integer id) { 26 | this.id = id; 27 | } 28 | 29 | public String getPermissionCode() { 30 | return permissionCode; 31 | } 32 | 33 | public void setPermissionCode(String permissionCode) { 34 | this.permissionCode = permissionCode; 35 | } 36 | 37 | public String getPermissionName() { 38 | return permissionName; 39 | } 40 | 41 | public void setPermissionName(String permissionName) { 42 | this.permissionName = permissionName; 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/service/SysRequestPathService.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.service; 2 | 3 | import com.spring.security.entity.SysRequestPath; 4 | import java.util.List; 5 | 6 | /** 7 | * 请求路径(SysRequestPath)表服务接口 8 | * 9 | * @author makejava 10 | * @since 2019-09-04 17:11:16 11 | */ 12 | public interface SysRequestPathService { 13 | 14 | /** 15 | * 通过ID查询单条数据 16 | * 17 | * @param id 主键 18 | * @return 实例对象 19 | */ 20 | SysRequestPath queryById(Integer id); 21 | 22 | /** 23 | * 查询多条数据 24 | * 25 | * @param offset 查询起始位置 26 | * @param limit 查询条数 27 | * @return 对象列表 28 | */ 29 | List queryAllByLimit(int offset, int limit); 30 | 31 | /** 32 | * 新增数据 33 | * 34 | * @param sysRequestPath 实例对象 35 | * @return 实例对象 36 | */ 37 | SysRequestPath insert(SysRequestPath sysRequestPath); 38 | 39 | /** 40 | * 修改数据 41 | * 42 | * @param sysRequestPath 实例对象 43 | * @return 实例对象 44 | */ 45 | SysRequestPath update(SysRequestPath sysRequestPath); 46 | 47 | /** 48 | * 通过主键删除数据 49 | * 50 | * @param id 主键 51 | * @return 是否成功 52 | */ 53 | boolean deleteById(Integer id); 54 | 55 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/config/handler/CustomizeLogoutSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.config.handler; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.spring.security.common.entity.JsonResult; 5 | import com.spring.security.common.utils.ResultTool; 6 | import org.springframework.security.core.Authentication; 7 | import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; 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 | * @Author: Hutengfei 17 | * @Description: 登出成功处理逻辑 18 | * @Date Create in 2019/9/4 10:17 19 | */ 20 | @Component 21 | public class CustomizeLogoutSuccessHandler implements LogoutSuccessHandler { 22 | @Override 23 | public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { 24 | JsonResult result = ResultTool.success(); 25 | httpServletResponse.setContentType("text/json;charset=utf-8"); 26 | httpServletResponse.getWriter().write(JSON.toJSONString(result)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/service/SysUserService.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.service; 2 | 3 | import com.spring.security.entity.SysUser; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * 用户表(SysUser)表服务接口 9 | * 10 | * @author makejava 11 | * @since 2019-08-29 15:22:19 12 | */ 13 | public interface SysUserService { 14 | 15 | /** 16 | * 通过ID查询单条数据 17 | * 18 | * @param id 主键 19 | * @return 实例对象 20 | */ 21 | SysUser queryById(Integer id); 22 | 23 | /** 24 | * 查询多条数据 25 | * 26 | * @param offset 查询起始位置 27 | * @param limit 查询条数 28 | * @return 对象列表 29 | */ 30 | List queryAllByLimit(int offset, int limit); 31 | 32 | /** 33 | * 新增数据 34 | * 35 | * @param sysUser 实例对象 36 | * @return 实例对象 37 | */ 38 | SysUser insert(SysUser sysUser); 39 | 40 | /** 41 | * 修改数据 42 | * 43 | * @param sysUser 实例对象 44 | * @return 实例对象 45 | */ 46 | SysUser update(SysUser sysUser); 47 | 48 | /** 49 | * 通过主键删除数据 50 | * 51 | * @param id 主键 52 | * @return 是否成功 53 | */ 54 | boolean deleteById(Integer id); 55 | 56 | /** 57 | * 根据用户名查询用户 58 | * 59 | * @param userName 60 | * @return 61 | */ 62 | SysUser selectByName(String userName); 63 | 64 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/config/handler/CustomizeAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.config.handler; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.spring.security.common.entity.JsonResult; 5 | import com.spring.security.common.enums.ResultCode; 6 | import com.spring.security.common.utils.ResultTool; 7 | import org.springframework.security.core.AuthenticationException; 8 | import org.springframework.security.web.AuthenticationEntryPoint; 9 | import org.springframework.stereotype.Component; 10 | 11 | import javax.servlet.ServletException; 12 | import javax.servlet.http.HttpServletRequest; 13 | import javax.servlet.http.HttpServletResponse; 14 | import java.io.IOException; 15 | 16 | /** 17 | * @Author: Hutengfei 18 | * @Description: 匿名用户访问无权限资源时的异常 19 | * @Date Create in 2019/9/3 21:35 20 | */ 21 | @Component 22 | public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint { 23 | @Override 24 | public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { 25 | JsonResult result = ResultTool.fail(ResultCode.USER_NOT_LOGIN); 26 | httpServletResponse.setContentType("text/json;charset=utf-8"); 27 | httpServletResponse.getWriter().write(JSON.toJSONString(result)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/config/handler/CustomizeAccessDeniedHandler.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.config.handler; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.spring.security.common.entity.JsonResult; 5 | import com.spring.security.common.enums.ResultCode; 6 | import com.spring.security.common.utils.ResultTool; 7 | import org.springframework.security.access.AccessDeniedException; 8 | import org.springframework.security.web.access.AccessDeniedHandler; 9 | import org.springframework.stereotype.Component; 10 | 11 | import javax.servlet.ServletException; 12 | import javax.servlet.http.HttpServletRequest; 13 | import javax.servlet.http.HttpServletResponse; 14 | import java.io.IOException; 15 | 16 | /** 17 | * @Author: Hutengfei 18 | * @Description: 权限拒绝处理逻辑 19 | * @Date Create in 2019/9/3 20:56 20 | */ 21 | @Component 22 | public class CustomizeAccessDeniedHandler implements AccessDeniedHandler { 23 | 24 | @Override 25 | public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException { 26 | httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); 27 | JsonResult result = ResultTool.fail(ResultCode.NO_PERMISSION); 28 | httpServletResponse.setContentType("text/json;charset=utf-8"); 29 | httpServletResponse.getWriter().write(JSON.toJSONString(result)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/config/handler/CustomizeSessionInformationExpiredStrategy.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.config.handler; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.spring.security.common.entity.JsonResult; 5 | import com.spring.security.common.enums.ResultCode; 6 | import com.spring.security.common.utils.ResultTool; 7 | import org.springframework.security.web.session.SessionInformationExpiredEvent; 8 | import org.springframework.security.web.session.SessionInformationExpiredStrategy; 9 | import org.springframework.stereotype.Component; 10 | 11 | import javax.servlet.ServletException; 12 | import javax.servlet.http.HttpServletResponse; 13 | import java.io.IOException; 14 | 15 | /** 16 | * @Author: Hutengfei 17 | * @Description: 会话信息过期策略 18 | * @Date Create in 2019/9/4 9:34 19 | */ 20 | @Component 21 | public class CustomizeSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy { 22 | @Override 23 | public void onExpiredSessionDetected(SessionInformationExpiredEvent sessionInformationExpiredEvent) throws IOException, ServletException { 24 | JsonResult result = ResultTool.fail(ResultCode.USER_ACCOUNT_USE_BY_OTHERS); 25 | HttpServletResponse httpServletResponse = sessionInformationExpiredEvent.getResponse(); 26 | httpServletResponse.setContentType("text/json;charset=utf-8"); 27 | httpServletResponse.getWriter().write(JSON.toJSONString(result)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/dao/SysRequestPathDao.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.dao; 2 | 3 | import com.spring.security.entity.SysRequestPath; 4 | import org.apache.ibatis.annotations.Param; 5 | import java.util.List; 6 | 7 | /** 8 | * 请求路径(SysRequestPath)表数据库访问层 9 | * 10 | * @author makejava 11 | * @since 2019-09-04 17:11:16 12 | */ 13 | public interface SysRequestPathDao { 14 | 15 | /** 16 | * 通过ID查询单条数据 17 | * 18 | * @param id 主键 19 | * @return 实例对象 20 | */ 21 | SysRequestPath queryById(Integer id); 22 | 23 | /** 24 | * 查询指定行数据 25 | * 26 | * @param offset 查询起始位置 27 | * @param limit 查询条数 28 | * @return 对象列表 29 | */ 30 | List queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit); 31 | 32 | 33 | /** 34 | * 通过实体作为筛选条件查询 35 | * 36 | * @param sysRequestPath 实例对象 37 | * @return 对象列表 38 | */ 39 | List queryAll(SysRequestPath sysRequestPath); 40 | 41 | /** 42 | * 新增数据 43 | * 44 | * @param sysRequestPath 实例对象 45 | * @return 影响行数 46 | */ 47 | int insert(SysRequestPath sysRequestPath); 48 | 49 | /** 50 | * 修改数据 51 | * 52 | * @param sysRequestPath 实例对象 53 | * @return 影响行数 54 | */ 55 | int update(SysRequestPath sysRequestPath); 56 | 57 | /** 58 | * 通过主键删除数据 59 | * 60 | * @param id 主键 61 | * @return 影响行数 62 | */ 63 | int deleteById(Integer id); 64 | 65 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/service/SysRequestPathPermissionRelationService.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.service; 2 | 3 | import com.spring.security.entity.SysRequestPathPermissionRelation; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * 路径权限关联表(SysRequestPathPermissionRelation)表服务接口 9 | * 10 | * @author makejava 11 | * @since 2019-09-04 20:16:48 12 | */ 13 | public interface SysRequestPathPermissionRelationService { 14 | 15 | /** 16 | * 通过ID查询单条数据 17 | * 18 | * @param id 主键 19 | * @return 实例对象 20 | */ 21 | SysRequestPathPermissionRelation queryById(Integer id); 22 | 23 | /** 24 | * 查询多条数据 25 | * 26 | * @param offset 查询起始位置 27 | * @param limit 查询条数 28 | * @return 对象列表 29 | */ 30 | List queryAllByLimit(int offset, int limit); 31 | 32 | /** 33 | * 新增数据 34 | * 35 | * @param sysRequestPathPermissionRelation 实例对象 36 | * @return 实例对象 37 | */ 38 | SysRequestPathPermissionRelation insert(SysRequestPathPermissionRelation sysRequestPathPermissionRelation); 39 | 40 | /** 41 | * 修改数据 42 | * 43 | * @param sysRequestPathPermissionRelation 实例对象 44 | * @return 实例对象 45 | */ 46 | SysRequestPathPermissionRelation update(SysRequestPathPermissionRelation sysRequestPathPermissionRelation); 47 | 48 | /** 49 | * 通过主键删除数据 50 | * 51 | * @param id 主键 52 | * @return 是否成功 53 | */ 54 | boolean deleteById(Integer id); 55 | 56 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/dao/SysUserDao.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.dao; 2 | 3 | import com.spring.security.entity.SysUser; 4 | import org.apache.ibatis.annotations.Param; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * 用户表(SysUser)表数据库访问层 10 | * 11 | * @author makejava 12 | * @since 2019-09-03 15:06:50 13 | */ 14 | public interface SysUserDao { 15 | 16 | /** 17 | * 通过ID查询单条数据 18 | * 19 | * @param id 主键 20 | * @return 实例对象 21 | */ 22 | SysUser queryById(Integer id); 23 | 24 | /** 25 | * 查询指定行数据 26 | * 27 | * @param offset 查询起始位置 28 | * @param limit 查询条数 29 | * @return 对象列表 30 | */ 31 | List queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit); 32 | 33 | 34 | /** 35 | * 通过实体作为筛选条件查询 36 | * 37 | * @param sysUser 实例对象 38 | * @return 对象列表 39 | */ 40 | List queryAll(SysUser sysUser); 41 | 42 | /** 43 | * 新增数据 44 | * 45 | * @param sysUser 实例对象 46 | * @return 影响行数 47 | */ 48 | int insert(SysUser sysUser); 49 | 50 | /** 51 | * 修改数据 52 | * 53 | * @param sysUser 实例对象 54 | * @return 影响行数 55 | */ 56 | int update(SysUser sysUser); 57 | 58 | /** 59 | * 通过主键删除数据 60 | * 61 | * @param id 主键 62 | * @return 影响行数 63 | */ 64 | int deleteById(Integer id); 65 | 66 | /** 67 | * 根据用户名查询用户 68 | * 69 | * @param userName 70 | * @return 71 | */ 72 | SysUser selectByName(String userName); 73 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/service/SysPermissionService.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.service; 2 | 3 | import com.spring.security.entity.SysPermission; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * 权限表(SysPermission)表服务接口 9 | * 10 | * @author makejava 11 | * @since 2019-08-29 21:13:29 12 | */ 13 | public interface SysPermissionService { 14 | 15 | /** 16 | * 通过ID查询单条数据 17 | * 18 | * @param id 主键 19 | * @return 实例对象 20 | */ 21 | SysPermission queryById(Integer id); 22 | 23 | /** 24 | * 查询多条数据 25 | * 26 | * @param offset 查询起始位置 27 | * @param limit 查询条数 28 | * @return 对象列表 29 | */ 30 | List queryAllByLimit(int offset, int limit); 31 | 32 | /** 33 | * 新增数据 34 | * 35 | * @param sysPermission 实例对象 36 | * @return 实例对象 37 | */ 38 | SysPermission insert(SysPermission sysPermission); 39 | 40 | /** 41 | * 修改数据 42 | * 43 | * @param sysPermission 实例对象 44 | * @return 实例对象 45 | */ 46 | SysPermission update(SysPermission sysPermission); 47 | 48 | /** 49 | * 通过主键删除数据 50 | * 51 | * @param id 主键 52 | * @return 是否成功 53 | */ 54 | boolean deleteById(Integer id); 55 | 56 | /** 57 | * 查询用户的权限列表 58 | * 59 | * @param userId 60 | * @return 61 | */ 62 | List selectListByUser(Integer userId); 63 | 64 | /** 65 | * 查询具体某个接口的权限 66 | * 67 | * @param path 68 | * @return 69 | */ 70 | List selectListByPath(String path); 71 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/dao/SysRequestPathPermissionRelationDao.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.dao; 2 | 3 | import com.spring.security.entity.SysRequestPathPermissionRelation; 4 | import org.apache.ibatis.annotations.Param; 5 | import java.util.List; 6 | 7 | /** 8 | * 路径权限关联表(SysRequestPathPermissionRelation)表数据库访问层 9 | * 10 | * @author makejava 11 | * @since 2019-09-04 17:11:53 12 | */ 13 | public interface SysRequestPathPermissionRelationDao { 14 | 15 | /** 16 | * 通过ID查询单条数据 17 | * 18 | * @param 主键 19 | * @return 实例对象 20 | */ 21 | SysRequestPathPermissionRelation queryById( ); 22 | 23 | /** 24 | * 查询指定行数据 25 | * 26 | * @param offset 查询起始位置 27 | * @param limit 查询条数 28 | * @return 对象列表 29 | */ 30 | List queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit); 31 | 32 | 33 | /** 34 | * 通过实体作为筛选条件查询 35 | * 36 | * @param sysRequestPathPermissionRelation 实例对象 37 | * @return 对象列表 38 | */ 39 | List queryAll(SysRequestPathPermissionRelation sysRequestPathPermissionRelation); 40 | 41 | /** 42 | * 新增数据 43 | * 44 | * @param sysRequestPathPermissionRelation 实例对象 45 | * @return 影响行数 46 | */ 47 | int insert(SysRequestPathPermissionRelation sysRequestPathPermissionRelation); 48 | 49 | /** 50 | * 修改数据 51 | * 52 | * @param sysRequestPathPermissionRelation 实例对象 53 | * @return 影响行数 54 | */ 55 | int update(SysRequestPathPermissionRelation sysRequestPathPermissionRelation); 56 | 57 | /** 58 | * 通过主键删除数据 59 | * 60 | * @param 主键 61 | * @return 影响行数 62 | */ 63 | int deleteById( ); 64 | 65 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/dao/SysPermissionDao.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.dao; 2 | 3 | import com.spring.security.entity.SysPermission; 4 | import org.apache.ibatis.annotations.Param; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * 权限表(SysPermission)表数据库访问层 10 | * 11 | * @author makejava 12 | * @since 2019-08-29 21:13:29 13 | */ 14 | public interface SysPermissionDao { 15 | 16 | /** 17 | * 通过ID查询单条数据 18 | * 19 | * @param id 主键 20 | * @return 实例对象 21 | */ 22 | SysPermission queryById(Integer id); 23 | 24 | /** 25 | * 查询指定行数据 26 | * 27 | * @param offset 查询起始位置 28 | * @param limit 查询条数 29 | * @return 对象列表 30 | */ 31 | List queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit); 32 | 33 | 34 | /** 35 | * 通过实体作为筛选条件查询 36 | * 37 | * @param sysPermission 实例对象 38 | * @return 对象列表 39 | */ 40 | List queryAll(SysPermission sysPermission); 41 | 42 | /** 43 | * 新增数据 44 | * 45 | * @param sysPermission 实例对象 46 | * @return 影响行数 47 | */ 48 | int insert(SysPermission sysPermission); 49 | 50 | /** 51 | * 修改数据 52 | * 53 | * @param sysPermission 实例对象 54 | * @return 影响行数 55 | */ 56 | int update(SysPermission sysPermission); 57 | 58 | /** 59 | * 通过主键删除数据 60 | * 61 | * @param id 主键 62 | * @return 影响行数 63 | */ 64 | int deleteById(Integer id); 65 | 66 | /** 67 | * 查询用户的权限 68 | * 69 | * @param userId 70 | * @return 71 | */ 72 | List selectListByUser(Integer userId); 73 | 74 | /** 75 | * 查询具体某个接口的权限 76 | * 77 | * @param path 接口路径 78 | * @return 79 | */ 80 | List selectListByPath(String path); 81 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/config/handler/CustomizeAccessDecisionManager.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.config.handler; 2 | 3 | import org.springframework.security.access.AccessDecisionManager; 4 | import org.springframework.security.access.AccessDeniedException; 5 | import org.springframework.security.access.ConfigAttribute; 6 | import org.springframework.security.authentication.InsufficientAuthenticationException; 7 | import org.springframework.security.core.Authentication; 8 | import org.springframework.security.core.GrantedAuthority; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.util.Collection; 12 | import java.util.Iterator; 13 | 14 | /** 15 | * @Author: Hutengfei 16 | * @Description: 访问决策管理器 17 | * @Date Create in 2019/9/3 20:38 18 | */ 19 | @Component 20 | public class CustomizeAccessDecisionManager implements AccessDecisionManager { 21 | @Override 22 | public void decide(Authentication authentication, Object o, Collection collection) throws AccessDeniedException, InsufficientAuthenticationException { 23 | Iterator iterator = collection.iterator(); 24 | while (iterator.hasNext()) { 25 | ConfigAttribute ca = iterator.next(); 26 | //当前请求需要的权限 27 | String needRole = ca.getAttribute(); 28 | //当前用户所具有的权限 29 | Collection authorities = authentication.getAuthorities(); 30 | for (GrantedAuthority authority : authorities) { 31 | if (authority.getAuthority().equals(needRole)) { 32 | return; 33 | } 34 | } 35 | } 36 | throw new AccessDeniedException("权限不足!"); 37 | } 38 | 39 | @Override 40 | public boolean supports(ConfigAttribute configAttribute) { 41 | return true; 42 | } 43 | 44 | @Override 45 | public boolean supports(Class aClass) { 46 | return true; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: isoftstone-security 4 | datasource: 5 | type: com.zaxxer.hikari.HikariDataSource 6 | driver-class-name: com.mysql.cj.jdbc.Driver 7 | url: jdbc:mysql://localhost:3306/spring_security?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=CTT 8 | username: root 9 | password: root 10 | hikari: 11 | minimum-idle: 5 12 | idle-timeout: 600000 13 | maximum-pool-size: 10 14 | auto-commit: true 15 | pool-name: MyHikariCP 16 | max-lifetime: 1800000 17 | connection-timeout: 30000 18 | connection-test-query: SELECT 1 19 | server: 20 | port: 8666 21 | 22 | mybatis-plus: 23 | # 如果是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml 24 | # 如果是放在resource目录 classpath:/mapper/*Mapper.xml 25 | mapper-locations: classpath:mapper/*.xml, classpath:mybatis/mapping/**/*.xml 26 | #实体扫描,多个package用逗号或者分号分隔 27 | typeAliasesPackage: com.spring.** 28 | global-config: 29 | #主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID"; 30 | id-type: 0 31 | #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断" 32 | field-strategy: 1 33 | #驼峰下划线转换 34 | db-column-underline: true 35 | #刷新mapper 调试神器 36 | refresh-mapper: true 37 | #数据库大写下划线转换 38 | #capital-mode: true 39 | #序列接口实现类配置,不在推荐使用此方式进行配置,请使用自定义bean注入 40 | #key-generator: com.baomidou.mybatisplus.incrementer.H2KeyGenerator 41 | #逻辑删除配置(下面3个配置) 42 | logic-delete-value: 0 43 | logic-not-delete-value: 1 44 | #自定义sql注入器,不在推荐使用此方式进行配置,请使用自定义bean注入 45 | #sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector 46 | #自定义填充策略接口实现,不在推荐使用此方式进行配置,请使用自定义bean注入 47 | # meta-object-handler: com.baomidou.springboot.MyMetaObjectHandler 48 | #自定义SQL注入器 49 | #sql-injector: com.baomidou.springboot.xxx 50 | # SQL 解析缓存,开启后多租户 @SqlParser 注解生效 51 | sql-parser-cache: true 52 | configuration: 53 | map-underscore-to-camel-case: true 54 | cache-enabled: false -------------------------------------------------------------------------------- /src/main/java/com/spring/security/common/enums/ResultCode.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.common.enums; 2 | 3 | /** 4 | * @Author: Hutengfei 5 | * @Description: 返回码定义 6 | * 规定: 7 | * #1表示成功 8 | * #1001~1999 区间表示参数错误 9 | * #2001~2999 区间表示用户错误 10 | * #3001~3999 区间表示接口异常 11 | * @Date Create in 2019/7/22 19:28 12 | */ 13 | public enum ResultCode { 14 | /* 成功 */ 15 | SUCCESS(200, "成功"), 16 | 17 | /* 默认失败 */ 18 | COMMON_FAIL(999, "失败"), 19 | 20 | /* 参数错误:1000~1999 */ 21 | PARAM_NOT_VALID(1001, "参数无效"), 22 | PARAM_IS_BLANK(1002, "参数为空"), 23 | PARAM_TYPE_ERROR(1003, "参数类型错误"), 24 | PARAM_NOT_COMPLETE(1004, "参数缺失"), 25 | 26 | /* 用户错误 */ 27 | USER_NOT_LOGIN(2001, "用户未登录"), 28 | USER_ACCOUNT_EXPIRED(2002, "账号已过期"), 29 | USER_CREDENTIALS_ERROR(2003, "密码错误"), 30 | USER_CREDENTIALS_EXPIRED(2004, "密码过期"), 31 | USER_ACCOUNT_DISABLE(2005, "账号不可用"), 32 | USER_ACCOUNT_LOCKED(2006, "账号被锁定"), 33 | USER_ACCOUNT_NOT_EXIST(2007, "账号不存在"), 34 | USER_ACCOUNT_ALREADY_EXIST(2008, "账号已存在"), 35 | USER_ACCOUNT_USE_BY_OTHERS(2009, "账号下线"), 36 | 37 | /* 业务错误 */ 38 | NO_PERMISSION(3001, "没有权限"); 39 | private Integer code; 40 | private String message; 41 | 42 | ResultCode(Integer code, String message) { 43 | this.code = code; 44 | this.message = message; 45 | } 46 | 47 | public Integer getCode() { 48 | return code; 49 | } 50 | 51 | public void setCode(Integer code) { 52 | this.code = code; 53 | } 54 | 55 | public String getMessage() { 56 | return message; 57 | } 58 | 59 | public void setMessage(String message) { 60 | this.message = message; 61 | } 62 | 63 | /** 64 | * 根据code获取message 65 | * 66 | * @param code 67 | * @return 68 | */ 69 | public static String getMessageByCode(Integer code) { 70 | for (ResultCode ele : values()) { 71 | if (ele.getCode().equals(code)) { 72 | return ele.getMessage(); 73 | } 74 | } 75 | return null; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/service/impl/SysUserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.service.impl; 2 | 3 | import com.spring.security.dao.SysUserDao; 4 | import com.spring.security.entity.SysUser; 5 | import com.spring.security.service.SysUserService; 6 | import org.springframework.stereotype.Service; 7 | 8 | import javax.annotation.Resource; 9 | import java.util.List; 10 | 11 | /** 12 | * 用户表(SysUser)表服务实现类 13 | * 14 | * @author makejava 15 | * @since 2019-08-29 15:22:19 16 | */ 17 | @Service("sysUserService") 18 | public class SysUserServiceImpl implements SysUserService { 19 | @Resource 20 | private SysUserDao sysUserDao; 21 | 22 | /** 23 | * 通过ID查询单条数据 24 | * 25 | * @param id 主键 26 | * @return 实例对象 27 | */ 28 | @Override 29 | public SysUser queryById(Integer id) { 30 | return this.sysUserDao.queryById(id); 31 | } 32 | 33 | /** 34 | * 查询多条数据 35 | * 36 | * @param offset 查询起始位置 37 | * @param limit 查询条数 38 | * @return 对象列表 39 | */ 40 | @Override 41 | public List queryAllByLimit(int offset, int limit) { 42 | return this.sysUserDao.queryAllByLimit(offset, limit); 43 | } 44 | 45 | /** 46 | * 新增数据 47 | * 48 | * @param sysUser 实例对象 49 | * @return 实例对象 50 | */ 51 | @Override 52 | public SysUser insert(SysUser sysUser) { 53 | this.sysUserDao.insert(sysUser); 54 | return sysUser; 55 | } 56 | 57 | /** 58 | * 修改数据 59 | * 60 | * @param sysUser 实例对象 61 | * @return 实例对象 62 | */ 63 | @Override 64 | public SysUser update(SysUser sysUser) { 65 | this.sysUserDao.update(sysUser); 66 | return this.queryById(sysUser.getId()); 67 | } 68 | 69 | /** 70 | * 通过主键删除数据 71 | * 72 | * @param id 主键 73 | * @return 是否成功 74 | */ 75 | @Override 76 | public boolean deleteById(Integer id) { 77 | return this.sysUserDao.deleteById(id) > 0; 78 | } 79 | 80 | @Override 81 | public SysUser selectByName(String userName) { 82 | return this.sysUserDao.selectByName(userName); 83 | } 84 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/config/handler/CustomizeFilterInvocationSecurityMetadataSource.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.config.handler; 2 | 3 | import com.spring.security.entity.SysPermission; 4 | import com.spring.security.service.SysPermissionService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.access.ConfigAttribute; 7 | import org.springframework.security.access.SecurityConfig; 8 | import org.springframework.security.web.FilterInvocation; 9 | import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.util.AntPathMatcher; 12 | 13 | import java.util.Collection; 14 | import java.util.List; 15 | 16 | /** 17 | * @Author: Hutengfei 18 | * @Description: 19 | * @Date Create in 2019/9/3 21:06 20 | */ 21 | @Component 22 | public class CustomizeFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { 23 | AntPathMatcher antPathMatcher = new AntPathMatcher(); 24 | @Autowired 25 | SysPermissionService sysPermissionService; 26 | @Override 27 | public Collection getAttributes(Object o) throws IllegalArgumentException { 28 | //获取请求地址 29 | String requestUrl = ((FilterInvocation) o).getRequestUrl(); 30 | 31 | //查询具体某个接口的权限 32 | List permissionList = sysPermissionService.selectListByPath(requestUrl); 33 | if(permissionList == null || permissionList.size() == 0){ 34 | //请求路径没有配置权限,表明该请求接口可以任意访问 35 | return null; 36 | } 37 | String[] attributes = new String[permissionList.size()]; 38 | for(int i = 0;i getAllConfigAttributes() { 46 | return null; 47 | } 48 | 49 | @Override 50 | public boolean supports(Class aClass) { 51 | return true; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/service/impl/SysRequestPathServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.service.impl; 2 | 3 | import com.spring.security.entity.SysRequestPath; 4 | import com.spring.security.dao.SysRequestPathDao; 5 | import com.spring.security.service.SysRequestPathService; 6 | import org.springframework.stereotype.Service; 7 | 8 | import javax.annotation.Resource; 9 | import java.util.List; 10 | 11 | /** 12 | * 请求路径(SysRequestPath)表服务实现类 13 | * 14 | * @author makejava 15 | * @since 2019-09-04 17:11:16 16 | */ 17 | @Service("sysRequestPathService") 18 | public class SysRequestPathServiceImpl implements SysRequestPathService { 19 | @Resource 20 | private SysRequestPathDao sysRequestPathDao; 21 | 22 | /** 23 | * 通过ID查询单条数据 24 | * 25 | * @param id 主键 26 | * @return 实例对象 27 | */ 28 | @Override 29 | public SysRequestPath queryById(Integer id) { 30 | return this.sysRequestPathDao.queryById(id); 31 | } 32 | 33 | /** 34 | * 查询多条数据 35 | * 36 | * @param offset 查询起始位置 37 | * @param limit 查询条数 38 | * @return 对象列表 39 | */ 40 | @Override 41 | public List queryAllByLimit(int offset, int limit) { 42 | return this.sysRequestPathDao.queryAllByLimit(offset, limit); 43 | } 44 | 45 | /** 46 | * 新增数据 47 | * 48 | * @param sysRequestPath 实例对象 49 | * @return 实例对象 50 | */ 51 | @Override 52 | public SysRequestPath insert(SysRequestPath sysRequestPath) { 53 | this.sysRequestPathDao.insert(sysRequestPath); 54 | return sysRequestPath; 55 | } 56 | 57 | /** 58 | * 修改数据 59 | * 60 | * @param sysRequestPath 实例对象 61 | * @return 实例对象 62 | */ 63 | @Override 64 | public SysRequestPath update(SysRequestPath sysRequestPath) { 65 | this.sysRequestPathDao.update(sysRequestPath); 66 | return this.queryById(sysRequestPath.getId()); 67 | } 68 | 69 | /** 70 | * 通过主键删除数据 71 | * 72 | * @param id 主键 73 | * @return 是否成功 74 | */ 75 | @Override 76 | public boolean deleteById(Integer id) { 77 | return this.sysRequestPathDao.deleteById(id) > 0; 78 | } 79 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/config/handler/CustomizeAuthenticationSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.config.handler; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.spring.security.common.entity.JsonResult; 5 | import com.spring.security.common.utils.ResultTool; 6 | import com.spring.security.entity.SysUser; 7 | import com.spring.security.service.SysUserService; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.security.core.Authentication; 10 | import org.springframework.security.core.context.SecurityContextHolder; 11 | import org.springframework.security.core.userdetails.User; 12 | import org.springframework.security.web.authentication.AuthenticationSuccessHandler; 13 | import org.springframework.stereotype.Component; 14 | 15 | import javax.servlet.ServletException; 16 | import javax.servlet.http.HttpServletRequest; 17 | import javax.servlet.http.HttpServletResponse; 18 | import java.io.IOException; 19 | import java.util.Date; 20 | 21 | /** 22 | * @Author: Hutengfei 23 | * @Description: 登录成功处理逻辑 24 | * @Date Create in 2019/9/3 15:52 25 | */ 26 | @Component 27 | public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler { 28 | @Autowired 29 | SysUserService sysUserService; 30 | 31 | @Override 32 | public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { 33 | //更新用户表上次登录时间、更新人、更新时间等字段 34 | User userDetails = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 35 | SysUser sysUser = sysUserService.selectByName(userDetails.getUsername()); 36 | sysUser.setLastLoginTime(new Date()); 37 | sysUser.setUpdateTime(new Date()); 38 | sysUser.setUpdateUser(sysUser.getId()); 39 | sysUserService.update(sysUser); 40 | 41 | //此处还可以进行一些处理,比如登录成功之后可能需要返回给前台当前用户有哪些菜单权限, 42 | //进而前台动态的控制菜单的显示等,具体根据自己的业务需求进行扩展 43 | 44 | //返回json数据 45 | JsonResult result = ResultTool.success(); 46 | httpServletResponse.setContentType("text/json;charset=utf-8"); 47 | httpServletResponse.getWriter().write(JSON.toJSONString(result)); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/config/handler/CustomizeAbstractSecurityInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.config.handler; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.access.SecurityMetadataSource; 5 | import org.springframework.security.access.intercept.AbstractSecurityInterceptor; 6 | import org.springframework.security.access.intercept.InterceptorStatusToken; 7 | import org.springframework.security.web.FilterInvocation; 8 | import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; 9 | import org.springframework.stereotype.Service; 10 | 11 | import javax.servlet.*; 12 | import java.io.IOException; 13 | 14 | /** 15 | * @Author: Hutengfei 16 | * @Description: 权限拦截器 17 | * @Date Create in 2019/9/4 16:25 18 | */ 19 | @Service 20 | public class CustomizeAbstractSecurityInterceptor extends AbstractSecurityInterceptor implements Filter { 21 | 22 | @Autowired 23 | private FilterInvocationSecurityMetadataSource securityMetadataSource; 24 | 25 | @Autowired 26 | public void setMyAccessDecisionManager(CustomizeAccessDecisionManager accessDecisionManager) { 27 | super.setAccessDecisionManager(accessDecisionManager); 28 | } 29 | 30 | @Override 31 | public Class getSecureObjectClass() { 32 | return FilterInvocation.class; 33 | } 34 | 35 | @Override 36 | public SecurityMetadataSource obtainSecurityMetadataSource() { 37 | return this.securityMetadataSource; 38 | } 39 | 40 | @Override 41 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 42 | FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain); 43 | invoke(fi); 44 | } 45 | 46 | public void invoke(FilterInvocation fi) throws IOException, ServletException { 47 | //fi里面有一个被拦截的url 48 | //里面调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限 49 | //再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够 50 | InterceptorStatusToken token = super.beforeInvocation(fi); 51 | try { 52 | //执行下一个拦截器 53 | fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); 54 | } finally { 55 | super.afterInvocation(token, null); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/config/service/UserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.config.service; 2 | 3 | import com.spring.security.entity.SysPermission; 4 | import com.spring.security.entity.SysUser; 5 | import com.spring.security.service.SysPermissionService; 6 | import com.spring.security.service.SysUserService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.security.core.GrantedAuthority; 9 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 10 | import org.springframework.security.core.userdetails.User; 11 | import org.springframework.security.core.userdetails.UserDetails; 12 | import org.springframework.security.core.userdetails.UserDetailsService; 13 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 14 | 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | /** 19 | * @Author: Hutengfei 20 | * @Description: 21 | * @Date Create in 2019/8/29 14:36 22 | */ 23 | public class UserDetailsServiceImpl implements UserDetailsService { 24 | @Autowired 25 | private SysUserService sysUserService; 26 | @Autowired 27 | private SysPermissionService sysPermissionService; 28 | 29 | @Override 30 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 31 | if (username == null || "".equals(username)) { 32 | throw new RuntimeException("用户不能为空"); 33 | } 34 | //根据用户名查询用户 35 | SysUser sysUser = sysUserService.selectByName(username); 36 | if (sysUser == null) { 37 | throw new RuntimeException("用户不存在"); 38 | } 39 | List grantedAuthorities = new ArrayList<>(); 40 | if (sysUser != null) { 41 | //获取该用户所拥有的权限 42 | List sysPermissions = sysPermissionService.selectListByUser(sysUser.getId()); 43 | // 声明用户授权 44 | sysPermissions.forEach(sysPermission -> { 45 | GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionCode()); 46 | grantedAuthorities.add(grantedAuthority); 47 | }); 48 | } 49 | return new User(sysUser.getAccount(), sysUser.getPassword(), sysUser.getEnabled(), sysUser.getAccountNonExpired(), sysUser.getCredentialsNonExpired(), sysUser.getAccountNonLocked(), grantedAuthorities); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/resources/mapper/SysRequestPathDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 18 | 19 | 20 | 26 | 27 | 28 | 44 | 45 | 46 | 47 | insert into sys_request_path(url, description) 48 | values (#{url}, #{description}) 49 | 50 | 51 | 52 | 53 | update sys_request_path 54 | 55 | 56 | url = #{url}, 57 | 58 | 59 | description = #{description}, 60 | 61 | 62 | where id = #{id} 63 | 64 | 65 | 66 | 67 | delete from sys_request_path where id = #{id} 68 | 69 | 70 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/service/impl/SysPermissionServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.service.impl; 2 | 3 | import com.spring.security.dao.SysPermissionDao; 4 | import com.spring.security.entity.SysPermission; 5 | import com.spring.security.service.SysPermissionService; 6 | import org.springframework.stereotype.Service; 7 | 8 | import javax.annotation.Resource; 9 | import java.util.List; 10 | 11 | /** 12 | * 权限表(SysPermission)表服务实现类 13 | * 14 | * @author makejava 15 | * @since 2019-08-29 21:13:29 16 | */ 17 | @Service("sysPermissionService") 18 | public class SysPermissionServiceImpl implements SysPermissionService { 19 | @Resource 20 | private SysPermissionDao sysPermissionDao; 21 | 22 | /** 23 | * 通过ID查询单条数据 24 | * 25 | * @param id 主键 26 | * @return 实例对象 27 | */ 28 | @Override 29 | public SysPermission queryById(Integer id) { 30 | return this.sysPermissionDao.queryById(id); 31 | } 32 | 33 | /** 34 | * 查询多条数据 35 | * 36 | * @param offset 查询起始位置 37 | * @param limit 查询条数 38 | * @return 对象列表 39 | */ 40 | @Override 41 | public List queryAllByLimit(int offset, int limit) { 42 | return this.sysPermissionDao.queryAllByLimit(offset, limit); 43 | } 44 | 45 | /** 46 | * 新增数据 47 | * 48 | * @param sysPermission 实例对象 49 | * @return 实例对象 50 | */ 51 | @Override 52 | public SysPermission insert(SysPermission sysPermission) { 53 | this.sysPermissionDao.insert(sysPermission); 54 | return sysPermission; 55 | } 56 | 57 | /** 58 | * 修改数据 59 | * 60 | * @param sysPermission 实例对象 61 | * @return 实例对象 62 | */ 63 | @Override 64 | public SysPermission update(SysPermission sysPermission) { 65 | this.sysPermissionDao.update(sysPermission); 66 | return this.queryById(sysPermission.getId()); 67 | } 68 | 69 | /** 70 | * 通过主键删除数据 71 | * 72 | * @param id 主键 73 | * @return 是否成功 74 | */ 75 | @Override 76 | public boolean deleteById(Integer id) { 77 | return this.sysPermissionDao.deleteById(id) > 0; 78 | } 79 | 80 | @Override 81 | public List selectListByUser(Integer userId) { 82 | return sysPermissionDao.selectListByUser(userId); 83 | } 84 | 85 | @Override 86 | public List selectListByPath(String path) { 87 | return sysPermissionDao.selectListByPath(path); 88 | } 89 | } -------------------------------------------------------------------------------- /src/main/java/com/spring/security/config/handler/CustomizeAuthenticationFailureHandler.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.config.handler; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.spring.security.common.entity.JsonResult; 5 | import com.spring.security.common.enums.ResultCode; 6 | import com.spring.security.common.utils.ResultTool; 7 | import org.springframework.security.authentication.*; 8 | import org.springframework.security.core.AuthenticationException; 9 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 10 | import org.springframework.stereotype.Component; 11 | 12 | import javax.servlet.ServletException; 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import java.io.IOException; 16 | 17 | /** 18 | * @Author: Hutengfei 19 | * @Description: 登录失败处理逻辑 20 | * @Date Create in 2019/9/3 15:52 21 | */ 22 | @Component 23 | public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler { 24 | 25 | 26 | @Override 27 | public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { 28 | //返回json数据 29 | JsonResult result = null; 30 | if (e instanceof AccountExpiredException) { 31 | //账号过期 32 | result = ResultTool.fail(ResultCode.USER_ACCOUNT_EXPIRED); 33 | } else if (e instanceof BadCredentialsException) { 34 | //密码错误 35 | result = ResultTool.fail(ResultCode.USER_CREDENTIALS_ERROR); 36 | } else if (e instanceof CredentialsExpiredException) { 37 | //密码过期 38 | result = ResultTool.fail(ResultCode.USER_CREDENTIALS_EXPIRED); 39 | } else if (e instanceof DisabledException) { 40 | //账号不可用 41 | result = ResultTool.fail(ResultCode.USER_ACCOUNT_DISABLE); 42 | } else if (e instanceof LockedException) { 43 | //账号锁定 44 | result = ResultTool.fail(ResultCode.USER_ACCOUNT_LOCKED); 45 | } else if (e instanceof InternalAuthenticationServiceException) { 46 | //用户不存在 47 | result = ResultTool.fail(ResultCode.USER_ACCOUNT_NOT_EXIST); 48 | }else{ 49 | //其他错误 50 | result = ResultTool.fail(ResultCode.COMMON_FAIL); 51 | } 52 | httpServletResponse.setContentType("text/json;charset=utf-8"); 53 | httpServletResponse.getWriter().write(JSON.toJSONString(result)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/service/impl/SysRequestPathPermissionRelationServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.service.impl; 2 | 3 | import com.spring.security.entity.SysRequestPathPermissionRelation; 4 | import com.spring.security.dao.SysRequestPathPermissionRelationDao; 5 | import com.spring.security.service.SysRequestPathPermissionRelationService; 6 | import org.springframework.stereotype.Service; 7 | 8 | import javax.annotation.Resource; 9 | import java.util.List; 10 | 11 | /** 12 | * 路径权限关联表(SysRequestPathPermissionRelation)表服务实现类 13 | * 14 | * @author makejava 15 | * @since 2019-09-04 20:16:50 16 | */ 17 | @Service("sysRequestPathPermissionRelationService") 18 | public class SysRequestPathPermissionRelationServiceImpl implements SysRequestPathPermissionRelationService { 19 | @Resource 20 | private SysRequestPathPermissionRelationDao sysRequestPathPermissionRelationDao; 21 | 22 | /** 23 | * 通过ID查询单条数据 24 | * 25 | * @param id 主键 26 | * @return 实例对象 27 | */ 28 | @Override 29 | public SysRequestPathPermissionRelation queryById(Integer id) { 30 | return this.sysRequestPathPermissionRelationDao.queryById(); 31 | } 32 | 33 | /** 34 | * 查询多条数据 35 | * 36 | * @param offset 查询起始位置 37 | * @param limit 查询条数 38 | * @return 对象列表 39 | */ 40 | @Override 41 | public List queryAllByLimit(int offset, int limit) { 42 | return this.sysRequestPathPermissionRelationDao.queryAllByLimit(offset, limit); 43 | } 44 | 45 | /** 46 | * 新增数据 47 | * 48 | * @param sysRequestPathPermissionRelation 实例对象 49 | * @return 实例对象 50 | */ 51 | @Override 52 | public SysRequestPathPermissionRelation insert(SysRequestPathPermissionRelation sysRequestPathPermissionRelation) { 53 | this.sysRequestPathPermissionRelationDao.insert(sysRequestPathPermissionRelation); 54 | return sysRequestPathPermissionRelation; 55 | } 56 | 57 | /** 58 | * 修改数据 59 | * 60 | * @param sysRequestPathPermissionRelation 实例对象 61 | * @return 实例对象 62 | */ 63 | @Override 64 | public SysRequestPathPermissionRelation update(SysRequestPathPermissionRelation sysRequestPathPermissionRelation) { 65 | this.sysRequestPathPermissionRelationDao.update(sysRequestPathPermissionRelation); 66 | return this.queryById(sysRequestPathPermissionRelation.getId()); 67 | } 68 | 69 | /** 70 | * 通过主键删除数据 71 | * 72 | * @param id 主键 73 | * @return 是否成功 74 | */ 75 | @Override 76 | public boolean deleteById(Integer id) { 77 | return this.sysRequestPathPermissionRelationDao.deleteById() > 0; 78 | } 79 | } -------------------------------------------------------------------------------- /src/main/resources/mapper/SysRequestPathPermissionRelationDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 18 | 19 | 20 | 26 | 27 | 28 | 44 | 45 | 46 | 47 | insert into sys_request_path_permission_relation(id, url_id, permission_id) 48 | values (#{id}, #{urlId}, #{permissionId}) 49 | 50 | 51 | 52 | 53 | update sys_request_path_permission_relation 54 | 55 | 56 | id = #{id}, 57 | 58 | 59 | url_id = #{urlId}, 60 | 61 | 62 | permission_id = #{permissionId}, 63 | 64 | 65 | where = #{id} 66 | 67 | 68 | 69 | 70 | delete from sys_request_path_permission_relation where = #{id} 71 | 72 | 73 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/common/entity/JsonResult.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.common.entity; 2 | 3 | import com.spring.security.common.enums.ResultCode; 4 | 5 | import java.io.Serializable; 6 | 7 | /** 8 | * @Author: Hutengfei 9 | * @Description: 统一返回实体 10 | * @Date Create in 2019/7/22 19:20 11 | */ 12 | public class JsonResult implements Serializable { 13 | private Boolean success; 14 | private Integer errorCode; 15 | private String errorMsg; 16 | private T data; 17 | 18 | public JsonResult() { 19 | } 20 | 21 | public JsonResult(boolean success) { 22 | this.success = success; 23 | this.errorCode = success ? ResultCode.SUCCESS.getCode() : ResultCode.COMMON_FAIL.getCode(); 24 | this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : ResultCode.COMMON_FAIL.getMessage(); 25 | } 26 | 27 | public JsonResult(boolean success, ResultCode resultEnum) { 28 | this.success = success; 29 | this.errorCode = success ? ResultCode.SUCCESS.getCode() : (resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode()); 30 | this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : (resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage()); 31 | } 32 | 33 | public JsonResult(boolean success, T data) { 34 | this.success = success; 35 | this.errorCode = success ? ResultCode.SUCCESS.getCode() : ResultCode.COMMON_FAIL.getCode(); 36 | this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : ResultCode.COMMON_FAIL.getMessage(); 37 | this.data = data; 38 | } 39 | 40 | public JsonResult(boolean success, ResultCode resultEnum, T data) { 41 | this.success = success; 42 | this.errorCode = success ? ResultCode.SUCCESS.getCode() : (resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode()); 43 | this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : (resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage()); 44 | this.data = data; 45 | } 46 | 47 | public Boolean getSuccess() { 48 | return success; 49 | } 50 | 51 | public void setSuccess(Boolean success) { 52 | this.success = success; 53 | } 54 | 55 | public Integer getErrorCode() { 56 | return errorCode; 57 | } 58 | 59 | public void setErrorCode(Integer errorCode) { 60 | this.errorCode = errorCode; 61 | } 62 | 63 | public String getErrorMsg() { 64 | return errorMsg; 65 | } 66 | 67 | public void setErrorMsg(String errorMsg) { 68 | this.errorMsg = errorMsg; 69 | } 70 | 71 | public T getData() { 72 | return data; 73 | } 74 | 75 | public void setData(T data) { 76 | this.data = data; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/resources/mapper/SysPermissionDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 18 | 19 | 20 | 26 | 27 | 28 | 44 | 45 | 46 | 47 | insert into sys_permission(permission_code, permission_name) 48 | values (#{permissionCode}, #{permissionName}) 49 | 50 | 51 | 52 | 53 | update sys_permission 54 | 55 | 56 | permission_code = #{permissionCode}, 57 | 58 | 59 | permission_name = #{permissionName}, 60 | 61 | 62 | where id = #{id} 63 | 64 | 65 | 66 | 67 | delete from sys_permission where id = #{id} 68 | 69 | 84 | 93 | 94 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/entity/SysUser.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.entity; 2 | 3 | import java.util.Date; 4 | import java.io.Serializable; 5 | 6 | /** 7 | * 用户表(SysUser)实体类 8 | * 9 | * @author makejava 10 | * @since 2019-09-03 15:06:48 11 | */ 12 | public class SysUser implements Serializable { 13 | private static final long serialVersionUID = 915478504870211231L; 14 | 15 | private Integer id; 16 | //账号 17 | private String account; 18 | //用户名 19 | private String userName; 20 | //用户密码 21 | private String password; 22 | //上一次登录时间 23 | private Date lastLoginTime; 24 | //账号是否可用。默认为1(可用) 25 | private Boolean enabled; 26 | //是否过期。默认为1(没有过期) 27 | private Boolean accountNonExpired; 28 | //账号是否锁定。默认为1(没有锁定) 29 | private Boolean accountNonLocked; 30 | //证书(密码)是否过期。默认为1(没有过期) 31 | private Boolean credentialsNonExpired; 32 | //创建时间 33 | private Date createTime; 34 | //修改时间 35 | private Date updateTime; 36 | //创建人 37 | private Integer createUser; 38 | //修改人 39 | private Integer updateUser; 40 | 41 | 42 | public Integer getId() { 43 | return id; 44 | } 45 | 46 | public void setId(Integer id) { 47 | this.id = id; 48 | } 49 | 50 | public String getAccount() { 51 | return account; 52 | } 53 | 54 | public void setAccount(String account) { 55 | this.account = account; 56 | } 57 | 58 | public String getUserName() { 59 | return userName; 60 | } 61 | 62 | public void setUserName(String userName) { 63 | this.userName = userName; 64 | } 65 | 66 | public String getPassword() { 67 | return password; 68 | } 69 | 70 | public void setPassword(String password) { 71 | this.password = password; 72 | } 73 | 74 | public Date getLastLoginTime() { 75 | return lastLoginTime; 76 | } 77 | 78 | public void setLastLoginTime(Date lastLoginTime) { 79 | this.lastLoginTime = lastLoginTime; 80 | } 81 | 82 | public Boolean getEnabled() { 83 | return enabled; 84 | } 85 | 86 | public void setEnabled(Boolean enabled) { 87 | this.enabled = enabled; 88 | } 89 | 90 | public Boolean getAccountNonExpired() { 91 | return accountNonExpired; 92 | } 93 | 94 | public void setAccountNonExpired(Boolean accountNonExpired) { 95 | this.accountNonExpired = accountNonExpired; 96 | } 97 | 98 | public Boolean getAccountNonLocked() { 99 | return accountNonLocked; 100 | } 101 | 102 | public void setAccountNonLocked(Boolean accountNonLocked) { 103 | this.accountNonLocked = accountNonLocked; 104 | } 105 | 106 | public Boolean getCredentialsNonExpired() { 107 | return credentialsNonExpired; 108 | } 109 | 110 | public void setCredentialsNonExpired(Boolean credentialsNonExpired) { 111 | this.credentialsNonExpired = credentialsNonExpired; 112 | } 113 | 114 | public Date getCreateTime() { 115 | return createTime; 116 | } 117 | 118 | public void setCreateTime(Date createTime) { 119 | this.createTime = createTime; 120 | } 121 | 122 | public Date getUpdateTime() { 123 | return updateTime; 124 | } 125 | 126 | public void setUpdateTime(Date updateTime) { 127 | this.updateTime = updateTime; 128 | } 129 | 130 | public Integer getCreateUser() { 131 | return createUser; 132 | } 133 | 134 | public void setCreateUser(Integer createUser) { 135 | this.createUser = createUser; 136 | } 137 | 138 | public Integer getUpdateUser() { 139 | return updateUser; 140 | } 141 | 142 | public void setUpdateUser(Integer updateUser) { 143 | this.updateUser = updateUser; 144 | } 145 | 146 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.7.RELEASE 9 | 10 | 11 | com.spring 12 | security 13 | 0.0.1-SNAPSHOT 14 | security 15 | 测试spring-security工程 16 | 17 | 18 | 1.8 19 | 5.1.6.RELEASE 20 | 1.2.46 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-web 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-test 32 | test 33 | 34 | 35 | 36 | org.springframework.security 37 | spring-security-web 38 | ${spring.security.version} 39 | 40 | 41 | org.springframework.security 42 | spring-security-config 43 | ${spring.security.version} 44 | 45 | 46 | 47 | com.zaxxer 48 | HikariCP 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-jdbc 53 | 54 | 55 | 56 | org.apache.tomcat 57 | tomcat-jdbc 58 | 59 | 60 | 61 | 62 | mysql 63 | mysql-connector-java 64 | ${mysql.version} 65 | 66 | 67 | 68 | com.baomidou 69 | mybatisplus-spring-boot-starter 70 | 1.0.5 71 | 72 | 73 | com.baomidou 74 | mybatis-plus 75 | 2.1.9 76 | 77 | 78 | org.projectlombok 79 | lombok 80 | 81 | 82 | 83 | com.alibaba 84 | fastjson 85 | ${fastjson.version} 86 | 87 | 88 | org.apache.commons 89 | commons-lang3 90 | 3.8.1 91 | 92 | 93 | 94 | 95 | 96 | 97 | org.springframework.boot 98 | spring-boot-maven-plugin 99 | 100 | 101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /src/main/java/com/spring/security/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.spring.security.config; 2 | 3 | import com.spring.security.config.handler.*; 4 | import com.spring.security.config.service.UserDetailsServiceImpl; 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.security.config.annotation.ObjectPostProcessor; 9 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 12 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 13 | import org.springframework.security.core.userdetails.UserDetailsService; 14 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 15 | import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; 16 | 17 | /** 18 | * @Author: Hutengfei 19 | * @Description: 20 | * @Date Create in 2019/8/28 20:15 21 | */ 22 | @Configuration 23 | @EnableWebSecurity 24 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 25 | //登录成功处理逻辑 26 | @Autowired 27 | CustomizeAuthenticationSuccessHandler authenticationSuccessHandler; 28 | 29 | //登录失败处理逻辑 30 | @Autowired 31 | CustomizeAuthenticationFailureHandler authenticationFailureHandler; 32 | 33 | //权限拒绝处理逻辑 34 | @Autowired 35 | CustomizeAccessDeniedHandler accessDeniedHandler; 36 | 37 | //匿名用户访问无权限资源时的异常 38 | @Autowired 39 | CustomizeAuthenticationEntryPoint authenticationEntryPoint; 40 | 41 | //会话失效(账号被挤下线)处理逻辑 42 | @Autowired 43 | CustomizeSessionInformationExpiredStrategy sessionInformationExpiredStrategy; 44 | 45 | //登出成功处理逻辑 46 | @Autowired 47 | CustomizeLogoutSuccessHandler logoutSuccessHandler; 48 | 49 | //访问决策管理器 50 | @Autowired 51 | CustomizeAccessDecisionManager accessDecisionManager; 52 | 53 | //实现权限拦截 54 | @Autowired 55 | CustomizeFilterInvocationSecurityMetadataSource securityMetadataSource; 56 | 57 | @Autowired 58 | private CustomizeAbstractSecurityInterceptor securityInterceptor; 59 | 60 | @Bean 61 | public UserDetailsService userDetailsService() { 62 | //获取用户账号密码及权限信息 63 | return new UserDetailsServiceImpl(); 64 | } 65 | 66 | @Bean 67 | public BCryptPasswordEncoder passwordEncoder() { 68 | // 设置默认的加密方式(强hash方式加密) 69 | return new BCryptPasswordEncoder(); 70 | } 71 | 72 | @Override 73 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 74 | auth.userDetailsService(userDetailsService()); 75 | } 76 | 77 | @Override 78 | protected void configure(HttpSecurity http) throws Exception { 79 | http.cors().and().csrf().disable(); 80 | http.authorizeRequests(). 81 | //antMatchers("/getUser").hasAuthority("query_user"). 82 | //antMatchers("/**").fullyAuthenticated(). 83 | withObjectPostProcessor(new ObjectPostProcessor() { 84 | @Override 85 | public O postProcess(O o) { 86 | o.setAccessDecisionManager(accessDecisionManager);//决策管理器 87 | o.setSecurityMetadataSource(securityMetadataSource);//安全元数据源 88 | return o; 89 | } 90 | }). 91 | //登出 92 | and().logout(). 93 | permitAll().//允许所有用户 94 | logoutSuccessHandler(logoutSuccessHandler).//登出成功处理逻辑 95 | deleteCookies("JSESSIONID").//登出之后删除cookie 96 | //登入 97 | and().formLogin(). 98 | permitAll().//允许所有用户 99 | successHandler(authenticationSuccessHandler).//登录成功处理逻辑 100 | failureHandler(authenticationFailureHandler).//登录失败处理逻辑 101 | //异常处理(权限拒绝、登录失效等) 102 | and().exceptionHandling(). 103 | accessDeniedHandler(accessDeniedHandler).//权限拒绝处理逻辑 104 | authenticationEntryPoint(authenticationEntryPoint).//匿名用户访问无权限资源时的异常处理 105 | //会话管理 106 | and().sessionManagement(). 107 | maximumSessions(1).//同一账号同时登录最大用户数 108 | expiredSessionStrategy(sessionInformationExpiredStrategy);//会话失效(账号被挤下线)处理逻辑 109 | http.addFilterBefore(securityInterceptor, FilterSecurityInterceptor.class); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | https://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | import java.io.File; 21 | import java.io.FileInputStream; 22 | import java.io.FileOutputStream; 23 | import java.io.IOException; 24 | import java.net.URL; 25 | import java.nio.channels.Channels; 26 | import java.nio.channels.ReadableByteChannel; 27 | import java.util.Properties; 28 | 29 | public class MavenWrapperDownloader { 30 | 31 | /** 32 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 33 | */ 34 | private static final String DEFAULT_DOWNLOAD_URL = 35 | "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; 36 | 37 | /** 38 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 39 | * use instead of the default one. 40 | */ 41 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 42 | ".mvn/wrapper/maven-wrapper.properties"; 43 | 44 | /** 45 | * Path where the maven-wrapper.jar will be saved to. 46 | */ 47 | private static final String MAVEN_WRAPPER_JAR_PATH = 48 | ".mvn/wrapper/maven-wrapper.jar"; 49 | 50 | /** 51 | * Name of the property which should be used to override the default download url for the wrapper. 52 | */ 53 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 54 | 55 | public static void main(String args[]) { 56 | System.out.println("- Downloader started"); 57 | File baseDirectory = new File(args[0]); 58 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 59 | 60 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 61 | // wrapperUrl parameter. 62 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 63 | String url = DEFAULT_DOWNLOAD_URL; 64 | if (mavenWrapperPropertyFile.exists()) { 65 | FileInputStream mavenWrapperPropertyFileInputStream = null; 66 | try { 67 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 68 | Properties mavenWrapperProperties = new Properties(); 69 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 70 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 71 | } catch (IOException e) { 72 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 73 | } finally { 74 | try { 75 | if (mavenWrapperPropertyFileInputStream != null) { 76 | mavenWrapperPropertyFileInputStream.close(); 77 | } 78 | } catch (IOException e) { 79 | // Ignore ... 80 | } 81 | } 82 | } 83 | System.out.println("- Downloading from: : " + url); 84 | 85 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 86 | if (!outputFile.getParentFile().exists()) { 87 | if (!outputFile.getParentFile().mkdirs()) { 88 | System.out.println( 89 | "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 90 | } 91 | } 92 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 93 | try { 94 | downloadFileFromURL(url, outputFile); 95 | System.out.println("Done"); 96 | System.exit(0); 97 | } catch (Throwable e) { 98 | System.out.println("- Error downloading"); 99 | e.printStackTrace(); 100 | System.exit(1); 101 | } 102 | } 103 | 104 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 105 | URL website = new URL(urlString); 106 | ReadableByteChannel rbc; 107 | rbc = Channels.newChannel(website.openStream()); 108 | FileOutputStream fos = new FileOutputStream(destination); 109 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 110 | fos.close(); 111 | rbc.close(); 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /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 https://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 | -------------------------------------------------------------------------------- /src/main/resources/mapper/SysUserDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 28 | 29 | 30 | 36 | 37 | 38 | 84 | 85 | 86 | 87 | insert into sys_user(account, user_name, password, last_login_time, enabled, account_non_expired, account_non_locked, credentials_non_expired, create_time, update_time, create_user, update_user) 88 | values (#{account}, #{userName}, #{password}, #{lastLoginTime}, #{enabled}, #{accountNonExpired}, #{accountNonLocked}, #{credentialsNonExpired}, #{createTime}, #{updateTime}, #{createUser}, #{updateUser}) 89 | 90 | 91 | 92 | 93 | update sys_user 94 | 95 | 96 | account = #{account}, 97 | 98 | 99 | user_name = #{userName}, 100 | 101 | 102 | password = #{password}, 103 | 104 | 105 | last_login_time = #{lastLoginTime}, 106 | 107 | 108 | enabled = #{enabled}, 109 | 110 | 111 | account_non_expired = #{accountNonExpired}, 112 | 113 | 114 | account_non_locked = #{accountNonLocked}, 115 | 116 | 117 | credentials_non_expired = #{credentialsNonExpired}, 118 | 119 | 120 | create_time = #{createTime}, 121 | 122 | 123 | update_time = #{updateTime}, 124 | 125 | 126 | create_user = #{createUser}, 127 | 128 | 129 | update_user = #{updateUser}, 130 | 131 | 132 | where id = #{id} 133 | 134 | 135 | 136 | 137 | delete from sys_user where id = #{id} 138 | 139 | 140 | 141 | 144 | -------------------------------------------------------------------------------- /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 | # https://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 | --------------------------------------------------------------------------------