springboot mybatisPlus集成shiro实现权限控制
创建数据库表。由于时间仓促,数据库表设计不太合理,后期会更改
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for sys_menu
-- ----------------------------
DROP TABLE IF EXISTS `sys_menu`;
CREATE TABLE `sys_menu` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
`menu_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '菜单名称',
`permission_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '权限ID',
`url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '请求路径',
`sort` tinyint(0) NULL DEFAULT NULL COMMENT '排序',
`style` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '样式(可设置css图标)',
`parent_id` int(0) NULL DEFAULT NULL COMMENT '父主键ID(有值的,属于该值菜单的下级菜单)',
`create_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(0) UNSIGNED NULL DEFAULT 0 COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '菜单表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sys_menu
-- ----------------------------
INSERT INTO `sys_menu` VALUES (1, '系统管理', '10001', NULL, 1, NULL, NULL, '88888888', '2021-03-23 15:09:11', NULL, NULL, 0);
INSERT INTO `sys_menu` VALUES (2, '权限管理', '10002', '/sys/permission', 2, NULL, 1, '88888888', '2021-03-23 15:09:11', NULL, NULL, 0);
INSERT INTO `sys_menu` VALUES (3, '角色管理', '10003', '/sys/role', 3, NULL, 1, '88888888', '2021-03-23 15:09:11', NULL, NULL, 0);
INSERT INTO `sys_menu` VALUES (4, '用户管理', '10004', '/sys/user', 4, NULL, 1, '88888888', '2021-03-23 15:09:11', NULL, NULL, 0);
-- ----------------------------
-- Table structure for sys_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_permission`;
CREATE TABLE `sys_permission` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
`permission_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '权限编码',
`permission_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '权限名称',
`description` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '描述说明',
`create_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(0) UNSIGNED NULL DEFAULT 0 COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 19 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '权限表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sys_permission
-- ----------------------------
INSERT INTO `sys_permission` VALUES (7, 'per:view', '查询权限', '接口权限', '1', '2021-03-23 15:11:42', NULL, NULL, 0);
INSERT INTO `sys_permission` VALUES (9, 'per:edit', '修改权限', '接口权限', '1', '2021-03-23 15:11:42', NULL, NULL, 0);
INSERT INTO `sys_permission` VALUES (11, 'role:view', '查询角色列表', '接口权限', '1', '2021-03-23 15:11:42', NULL, NULL, 0);
INSERT INTO `sys_permission` VALUES (13, 'role:edit', '修改角色', '接口权限', '1', '2021-03-23 15:11:42', NULL, NULL, 0);
INSERT INTO `sys_permission` VALUES (15, 'user:view', '查询用户列表', '接口权限', '1', '2021-03-23 15:11:42', NULL, NULL, 0);
INSERT INTO `sys_permission` VALUES (17, 'user:edit', '修改用户', '接口权限', '1', '2021-03-23 15:11:42', NULL, NULL, 0);
-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
`role_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色code',
`role_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色名称',
`create_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(1) NULL DEFAULT 0 COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '角色表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES (1, 'admin', '超级管理员', '1', '2021-03-23 15:18:10', NULL, NULL, 0);
INSERT INTO `sys_role` VALUES (2, 'group', '组长', '1', '2021-03-23 15:18:10', NULL, NULL, 0);
INSERT INTO `sys_role` VALUES (3, 'test', '测试员', '1', '2021-03-23 15:18:10', NULL, NULL, 0);
-- ----------------------------
-- Table structure for sys_role_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_permission`;
CREATE TABLE `sys_role_permission` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
`role_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色ID',
`permission_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '权限ID',
`create_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(1) NULL DEFAULT 0 COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 25 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '角色权限关联表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sys_role_permission
-- ----------------------------
INSERT INTO `sys_role_permission` VALUES (1, '1', '7', '1', '2021-03-23 15:29:09', NULL, NULL, 0);
INSERT INTO `sys_role_permission` VALUES (2, '1', '9', '1', '2021-03-23 15:29:09', NULL, NULL, 0);
INSERT INTO `sys_role_permission` VALUES (3, '1', '11', '1', '2021-03-23 15:29:09', NULL, NULL, 0);
INSERT INTO `sys_role_permission` VALUES (4, '1', '13', '1', '2021-03-23 15:29:09', NULL, NULL, 0);
INSERT INTO `sys_role_permission` VALUES (5, '1', '15', '1', '2021-03-23 15:29:09', NULL, NULL, 0);
INSERT INTO `sys_role_permission` VALUES (6, '1', '17', '1', '2021-03-23 15:29:09', NULL, NULL, 0);
INSERT INTO `sys_role_permission` VALUES (7, '2', '15', '1', '2021-03-23 15:29:09', NULL, NULL, 0);
INSERT INTO `sys_role_permission` VALUES (8, '2', '17', '1', '2021-03-23 15:29:09', NULL, NULL, 0);
INSERT INTO `sys_role_permission` VALUES (9, '2', '11', '1', '2021-03-23 15:29:09', NULL, NULL, 0);
INSERT INTO `sys_role_permission` VALUES (10, '3', '11', '1', '2021-03-23 15:29:09', NULL, NULL, 0);
INSERT INTO `sys_role_permission` VALUES (11, '3', '13', '1', '2021-03-23 15:29:09', NULL, NULL, 0);
-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户code',
`user_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名称',
`password` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码',
`create_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(1) NULL DEFAULT 0 COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES (1, 'admin', '超级管理员', '88888888', '1', '2021-03-23 15:51:27', NULL, NULL, 0);
INSERT INTO `sys_user` VALUES (2, 'zs', '张三', '123456', '1', '2021-03-23 15:51:27', NULL, NULL, 0);
INSERT INTO `sys_user` VALUES (3, 'ls', '李四', '123456', '1', '2021-03-23 15:51:27', NULL, NULL, 0);
-- ----------------------------
-- Table structure for sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户ID',
`role_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色ID',
`create_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(1) NULL DEFAULT 0 COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户角色关联表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sys_user_role
-- ----------------------------
INSERT INTO `sys_user_role` VALUES (1, '1', '1', '1', '2021-03-23 15:54:17', NULL, NULL, 0);
INSERT INTO `sys_user_role` VALUES (2, '2', '2', '1', '2021-03-23 15:54:17', NULL, NULL, 0);
INSERT INTO `sys_user_role` VALUES (3, '3', '3', '1', '2021-03-23 15:54:17', NULL, NULL, 0);
INSERT INTO `sys_user_role` VALUES (6, '1', '3', '1', '2021-03-23 15:54:17', NULL, NULL, 0);
INSERT INTO `sys_user_role` VALUES (7, '1', '2', '1', '2021-03-23 15:54:17', NULL, NULL, 0);
SET FOREIGN_KEY_CHECKS = 1;
pom文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- shiro start -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- shiro end -->
<!-- mysql start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- mysql end -->
<!-- mybatis-plus start -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!-- mybatis-plus end -->
<!-- mybatis-plus代码生成 start -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<!-- mybatis-plus代码生成 end -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
** 主启动类添加包扫描 **
@SpringBootApplication
@MapperScan(basePackages = "com.example.mapper")
public class ShirobootApplication {
public static void main(String[] args) {
SpringApplication.run(ShirobootApplication.class, args);
}
}
代码生成(网上找的别人的)
public class GeneratorCodeConfig {
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("zk");
gc.setOpen(false);
//实体属性 Swagger2 注解
gc.setSwagger2(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/logindatabase?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root1234");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));
pc.setParent("com.example");
pc.setEntity("model");
pc.setMapper("mapper");
pc.setService("service");
pc.setServiceImpl("service.impl");
mpg.setPackageInfo(pc);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setEntityLombokModel(true);
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
添加shiro配置类
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必须设置 SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// setLoginUrl 如果不设置值,默认会自动寻找Web工程根目录下的"/login.jsp"页面 或 "/login" 映射
shiroFilterFactoryBean.setLoginUrl("/notLogin");
// 设置无权限时跳转的 url;
shiroFilterFactoryBean.setUnauthorizedUrl("/notRole");
// 设置拦截器
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
//开放登陆接口
filterChainDefinitionMap.put("/login", "anon");
//其余接口一律拦截
//主要这行代码必须放在所有权限设置的最后,不然会导致所有 url 都被拦截
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
System.out.println("Shiro拦截器工厂类注入成功");
return shiroFilterFactoryBean;
}
/**
* 注入 securityManager
*/
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 设置realm.
securityManager.setRealm(customRealm());
return securityManager;
}
/**
* 自定义身份认证 realm;
* <p>
* 必须写这个类,并加上 @Bean 注解,目的是注入 CustomRealm,
* 否则会影响 CustomRealm类 中其他类的依赖注入
*/
@Bean
public CustomRealm customRealm() {
return new CustomRealm();
}
/**
* 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions)
* @return
*/
@Bean
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
/**
* 开启aop注解支持
* @param securityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
创建CustomRealm用于用户验证和权限控制
public class CustomRealm extends AuthorizingRealm {
@Autowired
private ISysUserService userService;
@Autowired
private ISysPermissionService sysPermissionService;
/**
* 获取身份验证信息
* Shiro中,最终是通过 Realm 来获取应用程序中的用户、角色及权限信息的。
*
* @param authenticationToken 用户身份信息 token
* @return 返回封装了用户信息的 AuthenticationInfo 实例
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("————身份认证方法————");
String password = "";
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
// 从数据库获取对应用户名密码的用户
QueryWrapper query = new QueryWrapper();
query.eq("user_name",token.getUsername());
SysUser user = userService.getOne(query);
if (user != null){
password = user.getPassword();
if (null == password) {
throw new AccountException("用户名不正确");
} else if (!password.equals(new String((char[]) token.getCredentials()))) {
throw new AccountException("密码不正确");
}
}else {
throw new AccountException("该用户不存在");
}
// 第一个参数保存为当前登陆人信息就可以使用 SecurityUtils.getSubject().getPrincipal() 获取登陆人信息
return new SimpleAuthenticationInfo(user, password, getName());
}
/**
* 获取授权信息
*
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("————权限认证————");
SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//获得该用户角色
Set<SysRole> sets = userService.getRole(user.getId());
Set<String> set = sets.stream().map(SysRole::getRoleCode).collect(Collectors.toSet());
Set<Integer> roleIds = sets.stream().map(SysRole::getId).collect(Collectors.toSet());
//设置该用户拥有的角色
info.setRoles(set);
Set<String> permissionSet = sysPermissionService.getPermissionByRole(roleIds);
info.setStringPermissions(permissionSet);
return info;
}
}
service
ISysUserService
public interface ISysUserService extends IService<SysUser> {
Set<SysRole> getRole(Integer id);
}
ISysPermissionService
public interface ISysPermissionService extends IService<SysPermission> {
Set<String> getPermissionByRole(Set<Integer> sets);
}
serviceImpl
ISysUserServiceImpl
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
@Autowired
private SysUserMapper userMapper;
@Override
public Set<SysRole> getRole(Integer id) {
return userMapper.getRole(id);
}
}
ISysPermissionServiceImpl
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {
@Autowired
private SysPermissionMapper sysPermissionMapper;
@Override
public Set<String> getPermissionByRole(Set<Integer> sets) {
return sysPermissionMapper.getPermissionByRole(sets);
}
}
mapper
ISysUserMapper
@Repository
public interface SysUserMapper extends BaseMapper<SysUser> {
Set<SysRole> getRole(Integer id);
}
ISysPermissionMapper
@Repository
public interface SysPermissionMapper extends BaseMapper<SysPermission> {
Set<String> getPermissionByRole(@Param("set") Set<Integer> sets);
}
mapper.xml
SysUserMapper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.SysUserMapper">
<select id="getRole" resultType="com.example.model.SysRole">
SELECT * FROM sys_role WHERE id IN (SELECT role_id FROM sys_user_role WHERE user_id = #{id})
</select>
</mapper>
SysPermissionMapper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.SysPermissionMapper">
<select id="getPermissionByRole" parameterType="java.util.Set" resultType="string">
SELECT
permission_code AS permissionCode
FROM
sys_permission
WHERE
id IN (
SELECT
permission_id
FROM
`sys_role_permission`
WHERE
<choose>
<when test="set !=null and set.size()>0">
role_id in
<foreach item="id" index="index" collection="set" open="(" separator="," close=")">
#{id}
</foreach>
</when>
<otherwise>
0 = 1
</otherwise>
</choose>
)
</select>
</mapper>
yml
server:
port: 8081
servlet:
context-path: /
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/logindatabase?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: root1234
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
auto-mapping-behavior: full
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath*:mapping/*Mapper.xml
global-config:
db-config:
logic-not-delete-value: 1
logic-delete-value: 0
编写登录controller
/**
* @author zk
* @Classname LoginController
* @Description TODO
* @Date 2021/6/11 17:17
*/
@RestController
public class LoginController {
@RequestMapping(value = "/notLogin", method = RequestMethod.GET)
public ResultInfo notLogin() {
return new ResultInfo(Status.SUCCESS.code,"您尚未登陆!");
}
@RequestMapping(value = "/notRole", method = RequestMethod.GET)
public ResultInfo notRole() {
return new ResultInfo(Status.SUCCESS.code,"您没有权限!");
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public ResultInfo logout() {
Subject subject = SecurityUtils.getSubject();
//注销
subject.logout();
return new ResultInfo(Status.SUCCESS.code,"成功注销!");
}
/**
* 登陆
*
* @param username 用户名
* @param password 密码
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResultInfo login(String username, String password) {
// 从SecurityUtils里边创建一个 subject
Subject subject = SecurityUtils.getSubject();
// 在认证提交前准备 token(令牌)
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// 执行认证登陆
subject.login(token);
return new ResultInfo(Status.SUCCESS.code,"登录成功");
}
}
编写异常处理ExceptionController
/**
* @author zk
* @Classname ExceptionController
* @Description TODO
* @Date 2021/6/11 17:14
*/
@RestControllerAdvice
public class ExceptionController {
@Autowired
private ResultInfo resultInfo;
@Autowired
public ExceptionController(ResultInfo resultMap) {
this.resultInfo = resultMap;
}
// 捕捉 CustomRealm 抛出的异常
@ExceptionHandler(AccountException.class)
public ResultInfo handleShiroException(Exception ex) {
return new ResultInfo(Status.SYSTEM_ERROR.code,ex.getMessage());
}
/**
* 访问接口没有权限
* @param e
* @return
*/
@ExceptionHandler(UnauthorizedException.class)
public ResultInfo handleShiroException1(Exception e) {
return new ResultInfo(Status.INSUFFICIENT_PERMISSION.code,e.getMessage()+"---"+Status.INSUFFICIENT_PERMISSION.message);
}
}
返回结果封装类以及返回码枚举类
/**
* @author zk
* @Classname ResultInfo
* @Description 返回参数格式封装类
* @Date 2021/6/11 11:28
*/
@Data
@Component
public class ResultInfo implements Serializable {
// 状态码
private Integer code;
// 消息
private String message;
// 数据对象
private Object result;
/**
* 无参构造器
*/
public ResultInfo() {
super();
}
public ResultInfo(Status status) {
super();
this.code = status.code;
this.message = status.message;
}
public ResultInfo result(Object result) {
this.result = result;
return this;
}
public ResultInfo message(String message) {
this.message = message;
return this;
}
/**
* 只返回状态,状态码,消息
*
* @param code
* @param message
*/
public ResultInfo(Integer code, String message) {
super();
this.code = code;
this.message = message;
}
/**
* 只返回状态,状态码,数据对象
*
* @param code
* @param result
*/
public ResultInfo(Integer code, Object result) {
super();
this.code = code;
this.result = result;
}
/**
* 返回全部信息即状态,状态码,消息,数据对象
*
* @param code
* @param message
* @param result
*/
public ResultInfo(Integer code, String message, Object result) {
super();
this.code = code;
this.message = message;
this.result = result;
}
}
/**
* @author zk
* @Classname Status
* @Description 返回值状态
* @Date 2021/6/11 11:29
*/
public enum Status {
// 公共
SUCCESS(2000, "成功"),
UNKNOWN_ERROR(9998,"未知异常"),
SYSTEM_ERROR(9999, "系统异常"),
INSUFFICIENT_PERMISSION(4003, "权限不足"),
WARN(9000, "失败"),
REQUEST_PARAMETER_ERROR(1002, "请求参数错误"),
// 登录
LOGIN_EXPIRE(2001, "未登录或者登录失效"),
LOGIN_CODE_ERROR(2002, "登录验证码错误"),
LOGIN_ERROR(2003, "用户名不存在或密码错误"),
LOGIN_USER_STATUS_ERROR(2004, "用户状态不正确"),
LOGOUT_ERROR(2005, "退出失败,token不存在"),
LOGIN_USER_NOT_EXIST(2006, "该用户不存在"),
LOGIN_USER_EXIST(2007, "该用户已存在");
public int code;
public String message;
Status(int code, String message) {
this.code = code;
this.message = message;
}
}
最后附上实体类
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class SysUser extends Model {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 用户名称
*/
private String userName;
/**
* 密码
*/
private String password;
/**
* 创建人
*/
private String createUser;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 修改人
*/
private String updateUser;
/**
* 修改时间
*/
private LocalDateTime updateTime;
/**
* 是否删除(0:正常/1:删除)
*/
private Boolean isDeleted;
}
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@NoArgsConstructor
public class SysPermission extends Model {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 权限code
*/
private String permissionCode;
/**
* 权限名称
*/
private String permissionName;
/**
* 描述说明
*/
private String description;
/**
* 创建人
*/
private String createUser;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 修改人
*/
private String updateUser;
/**
* 修改时间
*/
private LocalDateTime updateTime;
/**
* 是否删除(0:正常/1:删除)
*/
private Integer isDeleted;
}
刚开始写博客,只是用来平时记录,如果有什么遗漏或有问题的地方,希望各位大佬指出,谢谢。代码已上传至码云仓库链接
https://gitee.com/ObjectKang/shirodemo.git
有时再使用过程中会发现,再获取当前登陆人时,获取到的是用户名称,而不是对象,参考链接 https://blog.csdn.net/u013276512/article/details/81391681