Maven仓库:

dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.15</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.2.0</version></dependency><!-- 代码生成器 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.3.2</version></dependency><!-- 引擎模板--><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.2</version></dependency><!-- get set--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version><scope>provided</scope></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.3.2</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>

五个模型类,User(用户),Role(角色),UserRole(中间表),Permission(权限表),RolePermission(用户权限中间表)

package com.example.rbac.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;/*** <p>* �û���* </p>** @author mgk* @since 2020-07-16*/
@Data
@EqualsAndHashCode(callSuper = false)
public class User implements Serializable {private static final long serialVersionUID=1L;@TableId(value = "u_id", type = IdType.AUTO)private Integer uId;private String name;@TableField("passWord")private String passWord;private Integer status;@TableField("create_Time")private LocalDateTime createTime;@TableField("update_Time")private LocalDateTime updateTime;}
package com.example.rbac.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;/*** <p>* ��ɫ��* </p>** @author mgk* @since 2020-07-16*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Role implements Serializable {private static final long serialVersionUID=1L;@TableId(value = "role_id", type = IdType.AUTO)private Integer roleId;private String name;private Integer status;private LocalDateTime createTime;private LocalDateTime updateTime;}
package com.example.rbac.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;/*** <p>* * </p>** @author mgk* @since 2020-07-16*/
@Data
@EqualsAndHashCode(callSuper = false)
public class UserRole implements Serializable {private static final long serialVersionUID=1L;@TableId(value = "u_r_id", type = IdType.AUTO)private Integer uRId;private Integer uId;private Integer roleId;}
package com.example.rbac.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;/*** <p>* Ȩ�ޱ�* </p>** @author mgk* @since 2020-07-16*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Permission implements Serializable {private static final long serialVersionUID=1L;@TableId(value = "permission_id", type = IdType.AUTO)private Integer permissionId;private String title;private String action;private Integer status;private LocalDateTime createTime;private LocalDateTime updateTime;}
package com.example.rbac.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;/*** <p>* * </p>** @author mgk* @since 2020-07-16*/
@Data
@EqualsAndHashCode(callSuper = false)
public class RolePermission implements Serializable {private static final long serialVersionUID=1L;@TableId(value = "r_p_id", type = IdType.AUTO)private Integer rPId;private Integer roleId;private Integer permissionId;private LocalDateTime createTime;}

工具包:Result(返回类),ResuleCode(枚举类),自动生成代码类(CodeGenerator)

package com.example.util;import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {/*** <p>* 读取控制台内容* </p>*/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("mgk");gc.setOpen(false);// gc.setSwagger2(true); 实体属性 Swagger2 注解mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mgk?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");// dsc.setSchemaName("public");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("123456");mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();pc.setModuleName(scanner("模块名"));pc.setParent("com.example");mpg.setPackageInfo(pc);// 自定义配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};// 配置模板TemplateConfig templateConfig = new TemplateConfig();// 配置自定义输出模板//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别// templateConfig.setEntity("templates/entity2.java");// templateConfig.setService();// templateConfig.setController();templateConfig.setXml(null);mpg.setTemplate(templateConfig);// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");strategy.setEntityLombokModel(true);strategy.setRestControllerStyle(true);// 公共父类//strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");// 写于父类中的公共字段//strategy.setSuperEntityColumns("id");strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));strategy.setControllerMappingHyphenStyle(true);strategy.setTablePrefix(pc.getModuleName() + "_");mpg.setStrategy(strategy);//mpg.setTemplateEngine(new FreemarkerTemplateEngine());mpg.execute();}}
package com.example.util;import java.util.HashMap;
import java.util.Map;public class Result {private ResultCode code;//响应码private int status;private String message;//响应信息private Object body;//相应对象private Result() {this.code = ResultCode.SUCCESS;this.status=this.code.getCode();this.message=this.code.getMessage();this.body = null;}private Result(Object body,ResultCode code) {this.code = code;this.status=this.code.getCode();this.message=this.code.getMessage();this.body = body;}public static Result createFail(){Result result = new Result();result.status=ResultCode.FAIL.getCode();result.message=ResultCode.FAIL.getMessage();return result;}public static Result createResult(Object body,ResultCode code){return new Result(body, code);}public static Result createSuccessful(){return new Result();}public Map<String,Object> toJsonMap(){Map<String,Object> map = new HashMap<>();map.put("data",this.body);map.put("message",this.message);map.put("status",this.status);return  map;}
}
package com.example.util;public enum  ResultCode {SUCCESS(1001,"成功"),FAIL(1002,"失败"),WRONGPASSWORD(1101,"密码错误"),USERNOTEXIST(1102,"用户不存在"),USEREXIST(1103,"用户已存在"),USERNAMEERROR(1104,"用户名称错误"),USERNOTLOGIN(1105,"用户未登陆"),ROLEEXIST(1201,"权限已存在"),ROLEEXISTINSUFFICIENT (1202,"无访问操作权限");ResultCode(int code,String message) {this.message = message;this.code = code;}private int code;private String message;public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}
}

Service层两个类

package com.example.rbac.service;import com.example.rbac.entity.Role;
import com.example.rbac.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;import java.util.Set;/*** <p>* �û��� 服务类* </p>** @author mgk* @since 2020-07-16*/
public interface IUserService extends IService<User> {Set<Role> getUserRoles(Integer userId);
}
package com.example.rbac.service.impl;import com.example.rbac.entity.Role;
import com.example.rbac.entity.User;
import com.example.rbac.mapper.UserMapper;
import com.example.rbac.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.Set;/*** <p>* �û��� 服务实现类* </p>** @author mgk* @since 2020-07-16*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {@Autowired(required = true)private UserMapper userMapper;@Overridepublic Set<Role> getUserRoles(Integer userId) {return userMapper.getUserRoles(userId);}
}
package com.example.rbac.service.impl;import com.example.rbac.entity.Role;
import com.example.rbac.mapper.RoleMapper;
import com.example.rbac.mapper.UserMapper;
import com.example.rbac.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;import java.util.Set;/*** <p>* ��ɫ�� 服务实现类* </p>** @author mgk* @since 2020-07-16*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {}
package com.example.rbac.service;import com.example.rbac.entity.Role;
import com.baomidou.mybatisplus.extension.service.IService;/*** <p>* ��ɫ�� 服务类* </p>** @author mgk* @since 2020-07-16*/
public interface IRoleService extends IService<Role> {}

Mapper层

package com.example.rbac.mapper;import com.example.rbac.entity.Role;
import com.example.rbac.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;import java.util.Set;/*** <p>* �û��� Mapper 接口* </p>** @author mgk* @since 2020-07-16*/
public interface UserMapper extends BaseMapper<User> {@Select("select * from  role where role_id in(select role_id from user_role where u_id = #{userId})")Set<Role> getUserRoles(Integer userId);
}
package com.example.rbac.mapper;import com.example.rbac.entity.Role;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;/*** <p>* ��ɫ�� Mapper 接口* </p>** @author mgk* @since 2020-07-16*/
public interface RoleMapper extends BaseMapper<Role> {}

Controller层

package com.example.rbac.controller;import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.config.CustomRealm;
import com.example.rbac.entity.User;
import com.example.rbac.service.IUserService;
import com.example.rbac.service.impl.UserServiceImpl;
import com.example.util.Result;
import com.example.util.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.Map;/*** <p>* �û��� 前端控制器* </p>** @author mgk* @since 2020-07-16*/
@RestController
@RequestMapping("/rbac")
public class UserController {@Autowired(required = true)private IUserService userService;@Autowiredprivate CustomRealm myShiroRealm;@PostMapping("/login")public Map<String, Object> login(User user){Subject subject = SecurityUtils.getSubject();UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getName(),user.getPassWord());try {//进行验证,这里可以捕获异常,然后返回对应信息subject.login(usernamePasswordToken);} catch (AuthenticationException e) {e.printStackTrace();Result fail = Result.createResult(null, ResultCode.WRONGPASSWORD);return fail.toJsonMap();} catch (AuthorizationException e) {e.printStackTrace();}return Result.createResult(null, ResultCode.SUCCESS).toJsonMap();}/*** 注册用户* @return*/@PostMapping("/user")public Map<String, Object> registerUser(User user){QueryWrapper<User> wrapper = new QueryWrapper();wrapper.eq("name",user.getName());User one = userService.getOne(wrapper);if(!(one==null)){Result fail = Result.createResult(null, ResultCode.USEREXIST);return fail.toJsonMap();}if(StringUtils.isEmpty(user.getName())){Result fail = Result.createResult(null, ResultCode.USERNAMEERROR);return fail.toJsonMap();}userService.save(user);return Result.createSuccessful().toJsonMap();}
}
package com.example.rbac.controller;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.rbac.entity.Role;
import com.example.rbac.entity.User;
import com.example.rbac.service.IRoleService;
import com.example.util.Result;
import com.example.util.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.Map;/*** <p>* ��ɫ�� 前端控制器* </p>** @author mgk* @since 2020-07-16*/
@RestController
@RequestMapping("/rbac")
public class RoleController {@Autowired(required = true)private IRoleService roleService;/*** 添加角色* @param role* @return*/@PostMapping("/role")public Map<String,Object> addRole(Role  role){Subject subject = SecurityUtils.getSubject();if(subject.hasRole("viewManager")){System.out.println("有viewManager权限");}else {System.out.println("无viewManager权限");}QueryWrapper<Role> wrapper = new QueryWrapper();wrapper.eq("name",role.getName());Role one = roleService.getOne(wrapper);if(one!=null){Result fail = Result.createResult(null, ResultCode.ROLEEXIST);return fail.toJsonMap();}if(StringUtils.isEmpty(role.getName())){Result fail = Result.createResult(null, ResultCode.FAIL);return fail.toJsonMap();}roleService.save(role);Result fail = Result.createResult(null, ResultCode.SUCCESS);return fail.toJsonMap();}
}

主程序入口:

package com.example;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.example.rbac.mapper")
public class RbacApplication {public static void main(String[] args) {SpringApplication.run(RbacApplication.class, args);}}

sql数据:

INSERT INTO `user`(`u_id`, `name`, `passWord`, `status`, `create_Time`, `update_Time`) VALUES (2, 'mgk', '123456', 1, '2020-02-26 17:23:30', '2020-02-26 17:23:30');
INSERT INTO `user`(`u_id`, `name`, `passWord`, `status`, `create_Time`, `update_Time`) VALUES (7, 'admin', '123456', NULL, '2020-07-17 16:10:23', '2020-07-17 16:10:23');
INSERT INTO `user`(`u_id`, `name`, `passWord`, `status`, `create_Time`, `update_Time`) VALUES (8, '\"\"', '123456', NULL, '2020-07-17 16:33:19', '2020-07-17 16:33:19');
INSERT INTO `role`(`role_id`, `name`, `status`, `create_time`, `update_time`) VALUES (1, 'viewManager', NULL, '2020-07-20 10:42:36', '2020-07-20 10:42:36');
INSERT INTO `role`(`role_id`, `name`, `status`, `create_time`, `update_time`) VALUES (2, 'roleAddManager', NULL, '2020-07-20 10:43:05', '2020-07-20 10:43:05');
INSERT INTO `role`(`role_id`, `name`, `status`, `create_time`, `update_time`) VALUES (3, 'roleDelManager', NULL, '2020-07-20 10:43:13', '2020-07-20 10:43:13');
INSERT INTO `role`(`role_id`, `name`, `status`, `create_time`, `update_time`) VALUES (4, 'roleEditManager', NULL, '2020-07-20 10:43:20', '2020-07-20 10:43:20');INSERT INTO `user_role`(`u_r_id`, `u_id`, `role_id`) VALUES (1, 7, 1);
INSERT INTO `user_role`(`u_r_id`, `u_id`, `role_id`) VALUES (2, 7, 2);
INSERT INTO `user_role`(`u_r_id`, `u_id`, `role_id`) VALUES (3, 7, 3);
INSERT INTO `user_role`(`u_r_id`, `u_id`, `role_id`) VALUES (4, 7, 4);

SQL结构:

drop table if exists user;/*==============================================================*/
/* Table: user                                                  */
/*==============================================================*/
create table user
(u_id                 int not null auto_increment,name                 varchar(32),passWord             varchar(32),status               tinyint,create_Time          timestamp default CURRENT_TIMESTAMP,update_Time          timestamp default CURRENT_TIMESTAMP,primary key (u_id)
);alter table user comment '用户表';
drop table if exists role;/*==============================================================*/
/* Table: role                                                  */
/*==============================================================*/
create table role
(role_id              int not null auto_increment,name                 varchar(32),status               tinyint,create_time          timestamp default CURRENT_TIMESTAMP,update_time          timestamp default CURRENT_TIMESTAMP,primary key (role_id)
);alter table role comment '角色表';
drop table if exists user_role;/*==============================================================*/
/* Table: user_role                                             */
/*==============================================================*/
create table user_role
(u_r_id               int not null auto_increment,u_id                 int,role_id              int,primary key (u_r_id)
);alter table user_role add constraint FK_Reference_1 foreign key (u_id)references user (u_id) on delete restrict on update restrict;alter table user_role add constraint FK_Reference_2 foreign key (role_id)references role (role_id) on delete restrict on update restrict;
drop table if exists permission;/*==============================================================*/
/* Table: permission                                            */
/*==============================================================*/
create table permission
(permission_id        int not null auto_increment,title                varchar(50),action               varchar(50),status               tinyint,create_time          timestamp default CURRENT_TIMESTAMP,update_time          timestamp default CURRENT_TIMESTAMP,primary key (permission_id)
);alter table permission comment '权限表';
drop table if exists role_permission;/*==============================================================*/
/* Table: role_permission                                       */
/*==============================================================*/
create table role_permission
(r_p_id               int not null auto_increment,role_id              int,permission_id        int,create_time          timestamp,primary key (r_p_id)
);alter table role_permission add constraint FK_Reference_3 foreign key (role_id)references role (role_id) on delete restrict on update restrict;

表关系:

Shiro类,ShiroConfig(配置类)CustomReaml(自定义权限验证)

package com.example.config;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.rbac.entity.Role;
import com.example.rbac.entity.User;
import com.example.rbac.entity.UserRole;
import com.example.rbac.service.IUserRoleService;
import com.example.rbac.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;import java.security.Permissions;
import java.util.List;
import java.util.Map;
import java.util.Set;public class CustomRealm extends AuthorizingRealm {@Autowiredprivate IUserService userService;@Autowiredprivate IUserRoleService userRoleService;@Overridepublic AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {//获取登录用户名String name = (String) principalCollection.getPrimaryPrincipal();//根据用户名去数据库查询用户信息QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();userQueryWrapper.eq("name",name);User user = userService.getOne(userQueryWrapper);Set<Role> userRoles = userService.getUserRoles(user.getUId());//添加角色和权限SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        //角色关联表for (Role role : userRoles) {//添加角色simpleAuthorizationInfo.addRole(role.getName());//添加权限
//            for (Permissions permissions : role.getPermissions()) {
//                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
//            }}return simpleAuthorizationInfo;}@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {//加这一步的目的是在Post请求的时候会先进认证,然后在到请求if (authenticationToken.getPrincipal() == null) {return null;}//获取用户信息String name = authenticationToken.getPrincipal().toString();QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();userQueryWrapper.eq("name",name);User user = userService.getOne(userQueryWrapper);if (user == null) {//这里返回后会报出对应异常return null;} else {//这里验证authenticationToken和simpleAuthenticationInfo的信息SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, user.getPassWord().toString(), getName());return simpleAuthenticationInfo;}}
}
package com.example.config;import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.HashMap;
import java.util.Map;@Configuration
public class ShiroConfig {/*** 解决和Spring注解一起使用使,导致Shiro注解使用时不能被映射* @return*/
//    @Bean
//    @ConditionalOnMissingBean
//    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
//        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
//        defaultAAP.setProxyTargetClass(true);
//        return defaultAAP;
//    }//将自己的验证方式加入容器@Beanpublic CustomRealm myShiroRealm() {CustomRealm customRealm = new CustomRealm();return customRealm;}//权限管理,配置主要是Realm的管理认证@Beanpublic SecurityManager securityManager() {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();securityManager.setRealm(myShiroRealm());return securityManager;}//Filter工厂,设置对应的过滤条件和跳转条件@Beanpublic ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();shiroFilterFactoryBean.setSecurityManager(securityManager);Map<String, String> map = new HashMap<>();//登出map.put("/logout", "logout");//对所有用户认证map.put("/**", "authc");//登录shiroFilterFactoryBean.setLoginUrl("/rbac/login");//首页shiroFilterFactoryBean.setSuccessUrl("/index");//错误页面,认证不通过跳转shiroFilterFactoryBean.setUnauthorizedUrl("/error");shiroFilterFactoryBean.setFilterChainDefinitionMap(map);return shiroFilterFactoryBean;}//    /**
//     * 支持注解方式需要加入该Bean
//     * @param securityManager
//     * @return
//     */
//    @Bean
//    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
//        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
//        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
//        return authorizationAttributeSourceAdvisor;
//    }
}

配置文件:

server.port=9999
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mgk?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useTimezone=true
spring.datasource.username=root
spring.datasource.password=123456

手码不易点个赞再走吧谢谢啦

SpringBoot+Mybatis-Plus+Shiro整合的RBAC权限系统相关推荐

  1. Java项目学校教务教学管理系统源码,基于springboot+mybatis+layui+shiro+jquery开发

    Java学校教务管理系统源码 技术:springboot+mybatis+layui+shiro+jquery 运行环境:jdk8+mysql5.7+IntelliJ IDEA+maven  源码类型 ...

  2. Shiro整合SSO单点登录系统

    版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/m0_37797991/article/ ...

  3. 基于Springboot+mybatis+mysql+html教育培训中心教学系统

    基于Springboot+mybatis+mysql+html教育培训中心教学系统 一.系统介绍 二.功能展示 1.用户登陆 2.用户注册 3.个人中心 4.人员信息管理 5.课程管理 6.缴费管理 ...

  4. 基于Springboot+Mybatis+mysql+vue技术交流博客论坛系统

    基于Springboot+Mybatis+mysql+vue技术交流博客论坛系统 一.系统介绍 二.功能展示 1.主页(普通用户) 2.登陆.注册(普通用户) 3.博客(普通用户) 4.文章详情(点赞 ...

  5. Java+Springboot+Mybatis+Mysql+Bootstrap+Maven实现网上商城系统

    网上商城系统 一.系统介绍 1.软件环境 2.功能模块图 3.系统功能 4.数据库表 5.SQL语句 6.工程截图 二.系统展示 1.用户-浏览商品 2.用户-注册 3.用户-登录 4.用户-购物车管 ...

  6. springboot+mybatis+mysql+dubbo整合使用

    作为ssm的升级版框架springboot,在崇尚分布式,微服务的今天,越来越受到开发人员的喜爱和青睐,其优秀而简洁的配置,相比ssm的一大堆的xml配置文件,尤其在快速高效的敏捷开发节奏下,显得脱颖 ...

  7. 基于springboot+mybatis的高考志愿推荐及填报系统

    基于springboot+mybatis的高考志愿推荐系统+论文 高考志愿填报推荐系统的角色包括:用户考生和后台数据管理员. 各角色的只要功能如下: 用户考生 (1) 登录注册 (2) 信息查询(查询 ...

  8. 手撸一套RBAC权限系统

    文章来源:<RBAC权限系统分析.设计与实现> | shuwoom.com 目前,使用最普遍的权限管理模型正是RBAC(Role-Based Access Control)模型,这篇文章也 ...

  9. 基于RBAC 权限系统 功能权限 数据权限设计

    目录 功能权限 数据权限 权限设计 RBAC 鉴权管理,即权限判断逻辑. 授权管理,即权限分配过程. 功能权限 权限系统设计方案 权限系统就该这么设计 数据权限 数据权限就该这么实现(设计篇) 数据权 ...

最新文章

  1. java 手机号脱敏,身份证号脱敏 工具类
  2. Dom 学习总结及其实例
  3. 25个国外优秀电子商务网站设计案例
  4. 数据结构与算法 / 排序算法 / 堆排序
  5. 微信突然出现redirect_uri 参数错误
  6. XgBoost使用及调参教程
  7. php向bat中传递参数,php-将参数传递给PHPUnit
  8. SoapUI 测试http接口实战
  9. VMware ESXi 为虚拟机分配usb设备(硬盘)
  10. SpringBootSwagger构建REST API并生成API文档
  11. transactional replication 的immediate_sync属性
  12. android 创建目录/文件/读写文件
  13. miniconda安装BWA 以及miniconda的环境配置
  14. Java程序设计教程(第3版)雍俊海 全书例程-1
  15. 【C/C++】使用PDFLIB创建一个带中文的pdf文件
  16. ENVI Classic 分割标签制作
  17. AI换脸,流行一阵儿了;其中原理你一定也明白!
  18. 支付宝 android sdk 调用h,支付宝 iOS SDK 的简单使用
  19. 快手短视频怎么同步到头条?
  20. Rasa原文-生成NLU数据

热门文章

  1. 文件的元数据信息的含义及查看和修改
  2. django JsonResponse返回中文时显示unicode编码(\u67e5\u8be2)
  3. allrgro17.2转AD19方法,实测
  4. 为了旅游和梁定郊大吵一次,此行贿赠喜爱的朋友!!!
  5. 2021.12.15.梦开始的地方.
  6. 中国虚拟人哪家强?沙利文、IDC:小冰百度商汤位列第一梯队
  7. python 自动化获取博科光纤交换机端口信息
  8. open judge 1.7.1
  9. 纷享销客百思特 | 数字化营销赋能企业新增长沙龙圆满落幕
  10. SlashData开发者工具榜首等你而定!!!