创建数据库表。由于时间仓促,数据库表设计不太合理,后期会更改

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

springboot mybatisPlus集成shiro实现权限控制的更多相关文章

  1. springboot集成shiro 实现权限控制(转)

    shiro apache shiro 是一个轻量级的身份验证与授权框架,与spring security 相比较,简单易用,灵活性高,springboot本身是提供了对security的支持,毕竟是自 ...

  2. SpringBoot集成Shiro实现权限控制

    Shiro简介 Apache Shiro是一个功能强大且易于使用的Java安全框架,用于执行身份验证,授权,加密和会话管理.使用Shiro易于理解的API,您可以快速轻松地保护任何应用程序-从最小的移 ...

  3. 前后端分离结构中使用shiro进行权限控制

    前阵子在前后端分离项目中集成shiro项目,折腾了一下子,参考了网上一些博客,发现大多都还是之前传统的模式,并不适用于前后端分离结构.今天抽空整理了下demo,方便以后使用以及后来人参考. 一.spr ...

  4. springboot集成shiro实现权限认证

    github:https://github.com/peterowang/shiro 基于上一篇:springboot集成shiro实现身份认证 1.加入UserController package ...

  5. 轻松上手SpringBoot+SpringSecurity+JWT实RESTfulAPI权限控制实战

    前言 我们知道在项目开发中,后台开发权限认证是非常重要的,springboot 中常用熟悉的权限认证框架有,shiro,还有就是springboot 全家桶的 security当然他们各有各的好处,但 ...

  6. Shiro(二):Spring-boot如何集成Shiro(上)

    这篇文章主要介绍了spring-boot是如何集成shiro的authentication流程的. 从shiro-spring-boot-web-starter说起 shiro-spring-boot ...

  7. spring-boot-plus集成Shiro+JWT权限管理

    SpringBoot+Shiro+JWT权限管理 Shiro Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码和会话管理. 使用Shiro的易于理解的API,您可以 ...

  8. JAVAEE——BOS物流项目11:在realm中授权、shiro的方法注解权限控制、shiro的标签权限控制、总结shiro的权限控制方式、权限管理

    1 学习计划 1.在realm中进行授权 2.使用shiro的方法注解方式权限控制 n 在spring文件中配置开启shiro注解支持 n 在Action方法上使用注解 3.★使用shiro的标签进行 ...

  9. SpringBoot整合Shiro实现权限控制,验证码

    本文介绍 SpringBoot 整合 shiro,相对于 Spring Security 而言,shiro 更加简单,没有那么复杂. 目前我的需求是一个博客系统,有用户和管理员两种角色.一个用户可能有 ...

  10. SpringBoot整合Shiro实现权限控制

    目录 1.SpringBoot整合Shiro 1.1.shiro简介 1.2.代码的具体实现 1.2.1.Maven的配置 1.2.2.整合需要实现的类 1.2.3.项目结构 1.2.4.ShiroC ...

随机推荐

  1. 《Effective C++》定制new和delete

    Item49:了解new_handler的行为 当operator new抛出异常以反映出一个未获得满足的内存需求之前,它会先调用一个用户制定的错误处理函数,一个所谓的new-handler,为了制定 ...

  2. ClickHouse(11)ClickHouse合并树MergeTree家族表引擎之SummingMergeTree详细解析

    目录 建表语法 数据处理 汇总的通用规则 AggregateFunction 列中的汇总 嵌套结构数据的处理 资料分享 参考文章 SummingMergeTree引擎继承自MergeTree.区别在于 ...

  3. Linux文件常用操作命令

    Linux文件常用操作命令 一.Linux文件和目录简单操作 1.1 查看文件 ls 查看当前目录下的文件 如: -a 显示所有文件及目录 (ls内定将文件名或目录名称开头为"." ...

  4. python requests 最牛攻略

    目录 安装 Reuqests HTTP 简介 什么是 HTTP HTTP工作原理 HTTP的9种请求方法 HTTP状态码 requests 快速上手 requests 发起请求的步骤 requests ...

  5. [代码审计基础 03]-RCE-fork,system,execve

    RCE-fork,system,execve 简单来讲: 数据流进入了控制流 紧紧抓住输入 不同数据层的交汇处,往往是漏洞点 远程代码执行 PHP eval() assert() preg_reple ...

  6. JZOJ 3448.公路维护

    \(\text{Problem}\) 1.询问区间最小值是否大于 \(0\) 2.区间加(可正可负) 3.区间取 \(\max\) 如果某个数经过操作后小于等于 \(0\),以后的操作就不会再影响这个 ...

  7. Spring依赖注入问题

    记录一下最近复习的Spirng依赖注入问题 主要介绍两个注入方式 也是用的最多的 1.构造方法注入 2.Setter注入. 参考文档:https://blog.csdn.net/weixin_5541 ...

  8. 2020-6-2 map?

      问题描述 试题编号: 202006-2 试题名称: 稀疏向量 时间限制: 2.0s 内存限制: 512.0MB 问题描述:     #include<stdio.h>//数据量很大,所 ...

  9. 【RocketMQ】Dledger日志复制源码分析

    消息存储 在 [RocketMQ]消息的存储一文中提到,Broker收到消息后会调用CommitLog的asyncPutMessage方法写入消息,在DLedger模式下使用的是DLedgerComm ...

  10. 如何用revit+bimfilm快速完成径向动画制作

    推荐:将 NSDT场景编辑器 加入你的3D开发工具链. 在实际的施工中,我们会遇到诸如一些管道保温层包覆的施工内容,所以在制作它们的施工动画时,我们需要用径向剖切保温层来表达管道保温层包覆过程的施工状 ...