一、自定义RBAC表实现认证
创建自定义的用户表,角色表和用户角色关系表
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for sys_role -- ---------------------------- DROP TABLE IF EXISTS `sys_role`; CREATE TABLE `sys_role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `rolename` varchar(255) NOT NULL, `rolememo` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for sys_user -- ---------------------------- DROP TABLE IF EXISTS `sys_user`; CREATE TABLE `sys_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `realname` varchar(255) DEFAULT NULL, `isenable` varchar(255) NOT NULL, `islock` varchar(255) NOT NULL, `iscredentials` varchar(255) DEFAULT NULL, `createtime` datetime DEFAULT NULL, `logintime` datetime DEFAULT NULL, `isexpire` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; SET FOREIGN_KEY_CHECKS = 1; -- ---------------------------- -- Table structure for sys_user_role -- ---------------------------- DROP TABLE IF EXISTS `sys_user_role`; CREATE TABLE `sys_user_role` ( `userid` int(11) DEFAULT NULL, `roleid` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; SET FOREIGN_KEY_CHECKS = 1; 复制代码
创建Maven项目,加入依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </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> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> 复制代码
配置application.properties,配置数据库连接信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=root 复制代码
自定义类SysUser实体类
自定义类SysUser类代替Spring Security中的UserDetails类,实现UserDetails中的方法, 放在entity包中,同时新增实体类SysRole
public class SysUser implements UserDetails { private Integer id; private String username; private String password; private String realname; private boolean isExpired; private boolean isLocked; private boolean isCredentials; private boolean isEnabled; private Date createTime; private Date loginTime; private List<GrantedAuthority> authorities; public SysUser(){ } public SysUser(String username, String password, String realname, boolean isExpired, boolean isLocked, boolean isCredentials, boolean isEnabled, Date createTime, Date loginTime,List<GrantedAuthority> authorities) { this.username = username; this.password = password; this.realname = realname; this.isExpired = isExpired; this.isLocked = isLocked; this.isCredentials = isCredentials; this.isEnabled = isEnabled; this.createTime = createTime; this.loginTime = loginTime; this.authorities = authorities; } @Override public boolean isAccountNonExpired() { return isExpired; } @Override public boolean isAccountNonLocked() { return isLocked; } @Override public boolean isCredentialsNonExpired() { return isCredentials; } @Override public boolean isEnabled() { return isEnabled; } // 此处省略getter/setter/toString() } 复制代码
public class SysRole { private Integer id; private String name; private String memo; //此处省略getter/setter/toString方法 } 复制代码
创建SysUserMapper接口
创建mapper包,新建SysUserMapper接口,新增insertSysUser(), selectByUser()方法
@Repository public interface SysUserMapper { int insertSysUser(SysUser user); //根据账号名称,获取用户信息 SysUser selectSysUser(String username); } 复制代码
创建SysUserMapper.xml配置文件
在resource目录下新增mappers文件夹,新增SysUserMapper.xml配置文件
<?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.citi.mapper.SysUserMapper"> <resultMap id="userMapper" type="com.citi.entity.SysUser"> <id column="id" property="id"/> <result column="username" property="username"/> <result column="password" property="password" /> <result column="realname" property="realname" /> <result column="isenable" property="isEnabled" /> <result column="islock" property="isLocked" /> <result column="iscredentials" property="isCredentials" /> <result column="createtime" property="createTime" /> <result column="logintime" property="loginTime" /> <result column="isexpire" property="isExpired" /> </resultMap> <insert id="insertSysUser"> insert into sys_user(username,password,realname, isenable,islock,iscredentials,createtime,logintime) values(#{username},#{password},#{realname},#{isEnabled}, #{isLocked},#{isCredentials},#{createTime},#{loginTime}) </insert> <select id="selectSysUser" resultMap="userMapper"> select id, username,password,realname,isexpire, isenable,islock,iscredentials,createtime,logintime from sys_user where username=#{username} </select> </mapper> 复制代码
配置MyBatis
在application.properties配置文件总增加mybatis配置
# MyBatis设置 mybatis.mapper-locations=classpath:/mappers/*.xml mybatis.type-aliases-package=com.citi.entity 复制代码
创建启动类MainApplication
,新增jdbcInit()方法,在启动程序时初始化数据库,即往sys_user表里添加用户,创建三个用户Peter,Thor,Stark分别属于3个角色ADMIN,USER,READ,容器每次启动都会执行创建用户的操作,只在第一次启动时创建用户即可,创建完成之后可以将@PostConstruct注释即可
@MapperScan("com.citi.mapper") @SpringBootApplication public class MainApplication { @Resource private SysUserMapper sysUserMapper; @PostConstruct public void jdbcInit(){ List<GrantedAuthority> authorityList = new ArrayList<>(); // 角色名称需要以ROLE_开头,后面加上自定义的角色名称 GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + "ADMIN"); authorityList.add(authority); // 密码加密 PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); SysUser user = new SysUser("Peter",passwordEncoder.encode("12345"),"Peter Parker",true,true,true, true, new Date(),new Date(),authorityList); sysUserMapper.insertSysUser(user); } public static void main(String[] args) { SpringApplication.run(MainApplication.class,args); } } 复制代码
往sys_role,sys_user_role中添加数据