您好,登錄后才能下訂單哦!
這篇文章主要介紹“mybatisplus如何實現數據庫動態認證”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“mybatisplus如何實現數據庫動態認證”文章能幫助大家解決問題。
簡介
用戶表 ( sys_user ):保存用戶信息 角色表 ( sys_role ):保存角色信息 權限表 ( sys_permission ):保存系統資源信息。如:菜單、按鈕 和對應 URL它們的關系 :用戶表與角色表是 多對多關系 ,角色表與資源表是多對多關系。 用戶角色關系表(sys_user_role):用于維護用戶和角色的關系 角色資源關系表(sys_role_permission):用于維護角色與資源的關系
導入數據庫
步驟
# core模塊導入依賴 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> # web模塊導入依賴 <!--mybatis-plus啟動器--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> </dependency> <!--druid連接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> # web模塊配置yml spring: datasource: username: root password: 123456 url: jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8 #mysql8版本以上驅動包指定新的驅動類 driver-class-name: com.mysql.cj.jdbc.Driver # 數據源其他配置, 在 DruidConfig配置類中手動綁定 initialSize: 8 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL mybatis-plus: # 指定實體類所有包 type-aliases-package: com.ychen.security.model # 日志級別,會打印sql語句 logging: level: com.ychen.security.mapper: debug # 數據庫連接池配置類 @Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource dataSource() { return new DruidDataSource(); } } # mybatis plus配置類 @EnableTransactionManagement // 開啟事務管理 @MapperScan("com.ychen.security.mapper") // 掃描Mapper接口 @Configuration public class MybatisPlusConfig { /** * 分頁插件 * @return */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } } # 測試是否配置成功,啟動未報錯
編寫實體類
@Data public class SysUser implements UserDetails { @TableId(type = IdType.AUTO) // 表示主鍵自增長 private Long id; private String username; /** * 密碼需要通過加密后存儲 */ private String password; /** * 帳戶是否有效:1 未過期,0已過期 * 1 true * 0 false */ private boolean isAccountNonExpired = true; private boolean isAccountNonLocked = true; private boolean isCredentialsNonExpired = true; private boolean isEnabled = true; /** * 它不是sys_user表中的屬性,所以要進行標識,不然mybatis-plus會報錯 */ @TableField(exist = false) private Collection<? extends GrantedAuthority> authorities; private String nickName; private String mobile; private String email; private String createDate; private String updateDate; /** * 擁有角色集合 */ @TableField(exist = false) private List<com.ychen.security.model.SysRole> roleList = Lists.newArrayList(); /** * 獲取所有角色id */ @TableField(exist = false) private List<Long> roleIds = Lists.newArrayList(); public List<Long> getRoleIds() { if(CollectionUtils.isNotEmpty(roleList)) { roleIds = Lists.newArrayList(); for(com.ychen.security.model.SysRole role : roleList) { roleIds.add(role.getId()); } } return roleIds; } /** * 封裝當前用戶擁有的權限資源對象 */ @TableField(exist = false) private List<com.ychen.security.model.SysPermission> permissions = Lists.newArrayList(); } @Data public class SysRole implements Serializable { @TableId(type = IdType.AUTO) private Long id; /** * 角色名稱 */ private String name; /** * 角色描述 */ private String remark; private Date createDate; private Date updateDate; /** * 存儲當前角色的權限資源對象集合 * 修改角色時用到 */ @TableField(exist = false) private List<com.ychen.security.model.SysPermission> perList = Lists.newArrayList(); /** * 存儲當前角色的權限資源ID集合 * 修改角色時用到 */ @TableField(exist = false) private List<Long> perIds = Lists.newArrayList(); public List<Long> getPerIds() { if(CollectionUtils.isNotEmpty(perList)) { perIds = Lists.newArrayList(); for(com.ychen.security.model.SysPermission per : perList) { perIds.add(per.getId()); } } return perIds; } } @Data public class SysPermission implements Serializable { @TableId(type = IdType.AUTO) private Long id; /** * 父資源id,給它初始值 0 * 新增和修改頁面上默認的父資源id */ private Long parentId = 0L; /** * 用于新增和修改頁面上默認的根菜單名稱 */ @TableField(exist = false) private String parentName = "根菜單"; private String name; private String code; private String url; /** * 菜單:1,按鈕:2 */ private Integer type; private String icon; private String remark; private Date createDate; private Date updateDate; /** * 所有子權限對象集合 * 左側菜單渲染時要用 */ @TableField(exist = false) private List<SysPermission> children; /** * 所有子權限 URL 集合 * 左側菜單渲染時要用 */ @TableField(exist = false) private List<String> childrenUrl; }
測試mybatis plus是否可以使用
# mapper public interface SysUserMapper extends BaseMapper<SysUser> { } # service public interface SysUserService extends IService<SysUser> { } @Service public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService { } # controller測試 @RestController public class TestController2 { @Autowired SysUserService sysUserService; @GetMapping("/getTest") public String getTest(){ List<SysUser> list = sysUserService.list(); System.out.println(list); return "success"; } }
編寫用戶管理
# 業務層接口 public interface SysUserService extends IService<SysUser> { /** * 通過用戶名查詢用戶信息 * @param username 用戶名 * @return */ SysUser findByUsername(String username) ; } # 業務層實現類 @Service public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService { @Override public SysUser findByUsername(String username) { if(StringUtils.isEmpty(username)) { return null; } QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("username", username); // baseMapper 對應的是就是 SysUserMapper return baseMapper.selectOne(queryWrapper); } } # 控制層 @RestController @RequestMapping("/test") public class TestController2 { @Autowired SysUserService sysUserService; // 查詢單個 @GetMapping("/test2") public String test2(){ SysUser user = sysUserService.findByUsername("admin"); System.out.println("user: " + user); return "success"; } } # 控制臺 11:24:13.599 DEBUG 20080 --- [p-nio-80-exec-1] c.y.s.mapper.SysUserMapper.selectOne : ==> Preparing: SELECT id,update_date,nick_name,mobile,is_account_non_locked,password,is_account_non_expired,is_credentials_non_expired,is_enabled,email,username,create_date FROM sys_user WHERE (username = ?) 11:24:13.618 DEBUG 20080 --- [p-nio-80-exec-1] c.y.s.mapper.SysUserMapper.selectOne : ==> Parameters: admin(String) 11:24:13.651 DEBUG 20080 --- [p-nio-80-exec-1] c.y.s.mapper.SysUserMapper.selectOne : <== Total: 1 user: SysUser(id=9, username=admin, password=$2a$10$rDkPvvAFV8kqwvKJzwlRv.i.q.wz1w1pz0SFsHn/55jNeZFQv/eCm, isAccountNonExpired=true, isAccountNonLocked=true, isCredentialsNonExpired=true, isEnabled=true, authorities=null, nickName=夢學谷, mobile=16888888888, email=mengxu
編寫角色管理
# mapper public interface SysRoleMapper extends BaseMapper<SysRole> { } # 業務層接口 public interface SysRoleService extends IService<SysRole> { } # 業務層實現 @Service public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService { } # 接口 @Autowired SysRoleService sysRoleService; /** * 查詢角色表 */ @GetMapping("/test3") public String test3(){ SysRole role = sysRoleService.getById(9); System.out.println("role:" + role); return "success"; } # 控制臺 11:52:35.391 DEBUG 11852 --- [p-nio-80-exec-3] c.y.s.mapper.SysRoleMapper.selectById : ==> Preparing: SELECT id,update_date,name,remark,create_date FROM sys_role WHERE id=? 11:52:35.392 DEBUG 11852 --- [p-nio-80-exec-3] c.y.s.mapper.SysRoleMapper.selectById : ==> Parameters: 9(Integer) 11:52:35.414 DEBUG 11852 --- [p-nio-80-exec-3] c.y.s.mapper.SysRoleMapper.selectById : <== Total: 1 role:SysRole(id=9, name=超級管理員, remark=擁有所有的權限, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Tue Aug 08 11:11:11 GMT+08:00 2023, perList=[], perIds=[])
編寫權限管理
# mapper public interface SysPermissionMapper extends BaseMapper<SysPermission> { } # 業務層接口 public interface SysPermissionService extends IService<SysPermission> { } # 業務層實現 @Service public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService { } # 控制層接口 @Autowired SysPermissionService sysPermissionService; @GetMapping("/test4") public String test4(){ SysPermission permissions = sysPermissionService.getById(29); System.out.println("permissions:" + permissions); return "success"; } # 控制臺 11:50:03.198 DEBUG 11852 --- [p-nio-80-exec-1] c.y.s.m.SysPermissionMapper.selectById : ==> Preparing: SELECT id,update_date,code,icon,remark,type,parent_id,url,name,create_date FROM sys_permission WHERE id=? 11:50:03.210 DEBUG 11852 --- [p-nio-80-exec-1] c.y.s.m.SysPermissionMapper.selectById : ==> Parameters: 29(Integer) 11:50:03.266 DEBUG 11852 --- [p-nio-80-exec-1] c.y.s.m.SysPermissionMapper.selectById : <== Total: 1 permissions:SysPermission(id=29, parentId=28, parentName=根菜單, name=列表, code=sys:permission:list, url=null, type=2, icon=null, remark=權限列表, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Tue Aug 08 11:11:11 GMT+08:00 2023,
根據用戶id查詢該用戶所擁有的所有權限
# mapper public interface SysPermissionMapper extends BaseMapper<SysPermission> { // 根據用戶id查詢用戶所擁有的權限 List<SysPermission> selectPermissionByUserId(@Param("userId") Long userId); } <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ychen.security.mapper.SysPermissionMapper"> <select id="selectPermissionByUserId" resultType="SysPermission"> SELECT DISTINCT p.id, p.parent_id, p. NAME, p. CODE, p.url, p.type, p.icon, p.remark, p.create_date, p.update_date FROM sys_user AS u LEFT JOIN sys_user_role AS ur ON u.id = ur.user_id LEFT JOIN sys_role AS r ON ur.role_id = r.id LEFT JOIN sys_role_permission AS rp ON rp.role_id = r.id LEFT JOIN sys_permission AS p ON rp.permission_id = p.id WHERE u.id = #{userId} </select> </mapper> # 業務層接口 public interface SysPermissionService extends IService<SysPermission> { /** * 通過用戶id查詢所擁有權限 * @param userId * @return */ List<SysPermission> findByUserId(Long userId); } # 業務層實現 @Service public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService { @Override public List<SysPermission> findByUserId(Long userId) { if(userId == null) { return null; } List<SysPermission> permissionList = baseMapper.selectPermissionByUserId(userId); // 如果沒有權限,則將集合中的數據null移除 permissionList.remove(null); return permissionList; } } # 控制層接口 @RestController @RequestMapping("/test") public class TestController2 { @Autowired SysPermissionService sysPermissionService; @GetMapping("/test5") public String test5(){ List<SysPermission> permissions = sysPermissionService.findByUserId(9L); System.out.println(permissions); System.out.println("permissions:" + permissions.size()); return "success"; } } # 控制臺 13:23:56.820 DEBUG 19664 --- [p-nio-80-exec-1] c.y.s.m.S.selectPermissionByUserId : ==> Preparing: SELECT DISTINCT p.id, p.parent_id, p. NAME, p. CODE, p.url, p.type, p.icon, p.remark, p.create_date, p.update_date FROM sys_user AS u LEFT JOIN sys_user_role AS ur ON u.id = ur.user_id LEFT JOIN sys_role AS r ON ur.role_id = r.id LEFT JOIN sys_role_permission AS rp ON rp.role_id = r.id LEFT JOIN sys_permission AS p ON rp.permission_id = p.id WHERE u.id = ? 13:23:56.831 DEBUG 19664 --- [p-nio-80-exec-1] c.y.s.m.S.selectPermissionByUserId : ==> Parameters: 9(Long) 13:23:56.867 DEBUG 19664 --- [p-nio-80-exec-1] c.y.s.m.S.selectPermissionByUserId : <== Total: 17 [SysPermission(id=11, parentId=0, parentName=根菜單, name=首頁, code=sys:index, url=/, type=1, icon=fa fa-dashboard, remark=, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=17, parentId=0, parentName=根菜單, name=系統管理, code=sys:manage, url=null, type=1, icon=fa fa-cogs, remark=null, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=18, parentId=17, parentName=根菜單, name=用戶管理, code=sys:user, url=/user, type=1, icon=fa fa-users, remark=null, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=19, parentId=18, parentName=根菜單, name=列表, code=sys:user:list, url=, type=2, icon=, remark=員工列表, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Tue Aug 08 11:11:11 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=20, parentId=18, parentName=根菜單, name=新增, code=sys:user:add, url=, type=2, icon=, remark=新增用戶, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=21, parentId=18, parentName=根菜單, name=修改, code=sys:user:edit, url=, type=2, icon=, remark=修改用戶, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=22, parentId=18, parentName=根菜單, name=刪除, code=sys:user:delete, url=, type=2, icon=, remark=刪除用戶, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=23, parentId=17, parentName=根菜單, name=角色管理, code=sys:role, url=/role, type=1, icon=fa fa-user-secret, remark=null, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=24, parentId=23, parentName=根菜單, name=列表, code=sys:role:list, url=null, type=2, icon=null, remark=角色列表, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Tue Aug 08 11:11:11 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=25, parentId=23, parentName=根菜單, name=新增, code=sys:role:add, url=, type=2, icon=, remark=新增角色, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=26, parentId=23, parentName=根菜單, name=修改, code=sys:role:edit, url=, type=2, icon=, remark=修改角色, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=27, parentId=23, parentName=根菜單, name=刪除, code=sys:role:delete, url=, type=2, icon=, remark=刪除角色, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=28, parentId=17, parentName=根菜單, name=權限管理, code=sys:permission, url=/permission, type=1, icon=fa fa-cog, remark=null, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=29, parentId=28, parentName=根菜單, name=列表, code=sys:permission:list, url=null, type=2, icon=null, remark=權限列表, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Tue Aug 08 11:11:11 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=30, parentId=28, parentName=根菜單, name=新增, code=sys:permission:add, url=, type=2, icon=null, remark=新增權限, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=31, parentId=28, parentName=根菜單, name=修改, code=sys:permission:edit, url=, type=2, icon=null, remark=修改權限, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null), SysPermission(id=32, parentId=28, parentName=根菜單, name=刪除, code=sys:permission:delete, url=, type=2, icon=, remark=刪除權限, createDate=Tue Aug 08 11:11:11 GMT+08:00 2023, updateDate=Wed Aug 09 15:26:28 GMT+08:00 2023, children=null, childrenUrl=null)] permissions:17
用戶名密碼動態認證
@Component("customUserDetailsService") public class CustomUserDetailsService implements UserDetailsService { // 日志 Logger logger = LoggerFactory.getLogger(getClass()); // 加密方式 @Autowired PasswordEncoder passwordEncoder; // 用戶業務對象 @Autowired SysUserService sysUserService; // 權限對象 @Autowired SysPermissionService sysPermissionService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { logger.info("請求認證的用戶名: " + username); // 1. 通過請求的用戶名去數據庫中查詢用戶信息 SysUser sysUser = sysUserService.findByUsername(username); // 如果沒有查詢到,則拋出異常 if(sysUser == null) { throw new UsernameNotFoundException("用戶名或密碼錯誤"); } // 2. 查詢該用戶有哪一些權限 List<SysPermission> permissions = sysPermissionService.findByUserId(sysUser.getId()); // 如果該用戶沒有權限,則直接返回該對象 if(CollectionUtils.isEmpty(permissions)) { return sysUser; } /** * 如果有權限,則封裝到該對象中 * 在左側菜單 動態渲染會使用,目前先把它都傳入 */ sysUser.setPermissions(permissions); // 3. 封裝權限信息 List<GrantedAuthority> authorities = Lists.newArrayList(); for(SysPermission sp: permissions) { // 獲取到權限標識 String code = sp.getCode(); authorities.add(new SimpleGrantedAuthority(code)); } // 將封裝的權限信息添加到該對象中 sysUser.setAuthorities(authorities); // 4. 返回該對象,springsecurity自動進行身份認證 return sysUser; } }
手機號+短信動態認證
# 業務層接口 public interface SysUserService extends IService<SysUser> { /** * 通過手機號查詢用戶信息 * @param mobile 手機號 * @return */ SysUser findByMobile(String mobile); } # 業務層實現 @Service public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService { @Override public SysUser findByMobile(String mobile) { if(StringUtils.isEmpty(mobile)) { return null; } QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("mobile", mobile); // baseMapper 對應的是就是 SysUserMapper return baseMapper.selectOne(queryWrapper); } } # 實現UserDetailsService接口 @Component("mobileUserDetailsService") public class MobileUserDetailsService implements UserDetailsService { // 日志 Logger logger = LoggerFactory.getLogger(getClass()); // 用戶業務對象 @Autowired SysUserService sysUserService; // 權限對象 @Autowired SysPermissionService sysPermissionService; @Override public UserDetails loadUserByUsername(String mobile) throws UsernameNotFoundException { logger.info("請求的手機號是:" + mobile); // 1. 通過手機號查詢用戶信息 SysUser sysUser = sysUserService.findByMobile(mobile); // 判斷查詢到的用戶信息是否未空,為空則拋出異常 if(sysUser == null) { throw new UsernameNotFoundException("該手機號未注冊"); } // 2. 查詢該用戶所擁有的權限 List<SysPermission> permissions = sysPermissionService.findByUserId(sysUser.getId()); // 判斷查詢到的權限是否為空 if(CollectionUtils.isEmpty(permissions)) { return sysUser; } /** * 將查詢到的權限封裝到該對象中 * 在左側菜單 動態渲染會使用,目前先把它都傳入 */ sysUser.setPermissions(permissions); // 3. 封裝權限信息 List<GrantedAuthority> authorities = Lists.newArrayList(); for(SysPermission sp: permissions) { // 獲取到權限標識 String code = sp.getCode(); authorities.add(new SimpleGrantedAuthority(code)); } // 將權限設置給該用戶 sysUser.setAuthorities(authorities); // 4. 返回用戶對象,springsecurity自動進行身份認證 return sysUser; } }
關于“mybatisplus如何實現數據庫動態認證”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。