shiro+mysql动态验证

2.1、数据库设计
在实际开发中,用户名密码、角色、权限需要存在数据库中动态管理。一个简单的Shiro+MySQL的项目需要三张表,表结构及初始化数据如下:
shiro_user表:

DROP TABLE IF EXISTS `shiro_user`;
CREATE TABLE `shiro_user`  (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `USER_NAME` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  `PASSWORD` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  PRIMARY KEY (`ID`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
INSERT INTO `shiro_user` VALUES (1, 'test', '123456');

shiro_user_role表:

DROP TABLE IF EXISTS `shiro_user_role`;
CREATE TABLE `shiro_user_role`  (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `USER_NAME` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  `ROLE_NAME` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  PRIMARY KEY (`ID`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
INSERT INTO `shiro_user_role` VALUES (1, 'test', 'role1');

shiro_role_permission表:

DROP TABLE IF EXISTS `shiro_role_permission`;
CREATE TABLE `shiro_role_permission`  (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `ROLE_NAME` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  `PERM_NAME` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  PRIMARY KEY (`ID`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
INSERT INTO `shiro_role_permission` VALUES (1, 'role1', 'perm1');

2.2、添加依赖


    mysql
    mysql-connector-java
    5.1.32

2.3、配置文件
在resources文件夹下新建一个shiro.ini内容如下:

[main]
dataSource=org.springframework.jdbc.datasource.DriverManagerDataSource
#
dataSource.driverClassName=com.mysql.jdbc.Driver
# user:数据库名
dataSource.url=jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
# 用户名
dataSource.username=root
#如果数据库没有密码,就不要写这行
dataSource.password=123456
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
#是否检查权限
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.dataSource=$dataSource
#重写sql语句
#根据用户名查询出密码
jdbcRealm.authenticationQuery = select password from shiro_user where user_name = ?
#根据用户名查询出角色
jdbcRealm.userRolesQuery = select role_name from shiro_user_role where user_name = ?
#根据角色名查询出权限
jdbcRealm.permissionsQuery = select perm_name from shiro_role_permission where role_name = ?
securityManager.realms=$jdbcRealm

2.4、测试代码
跟上一篇的一样,看过的可以跳过

public class ShiroTest {
    private static final transient Logger log =
            LoggerFactory.getLogger(ShiroTest.class);

    public static void main(String[] args){
        //1、SecurityManager:classpath:shiro.ini
        Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        //2、解析配置文件,并返回一些SecurityManager
        SecurityManager securityManager = factory.getInstance();

        //3、SecurityManager绑定给SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);

        //4、安全操作,Subject是当前登录的用户
        Subject currentUser = SecurityUtils.getSubject();

        //5、测试在应用的当前回话中设置属性
        Session session = currentUser.getSession();

        //如果用户没有登陆过
        if(!currentUser.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken("test","123456");
            //记住我
            token.setRememberMe(true);
            try{
                currentUser.login(token);
                log.info("用户【"+currentUser.getPrincipal()+"】 登录成功");
                //登录之后查看是否拥有指定角色
                if(currentUser.hasRole("admin")){
                    log.info("有admin角色");
                }else{
                    log.info("没有admin角色");
                }
                if(currentUser.hasRole("role1")){
                    log.info("有role1角色");
                }else{
                    log.info("没有role1角色");
                }
                //查看用户是否拥有某个权限
                if(currentUser.isPermitted("perm1")){
                    log.info("有perm1权限");
                }else{
                    log.info("没有perm1权限");
                }
                if(currentUser.isPermitted("guest")){
                    log.info("有guest权限");
                }else{
                    log.info("没有guest权限");
                }
                //登出
                currentUser.logout();
            }catch (UnknownAccountException uae){
                log.info(token.getPrincipal()+" 账户不存在");
            }catch (IncorrectCredentialsException ice){
                log.info(token.getPrincipal()+" 密码不正确");
            }catch (LockedAccountException lae){
                log.info(token.getPrincipal()+" 用户被锁定了 ");
            }catch (AuthenticationException ae){
                //无法判断是什么错
                log.info(ae.getMessage());
            }
        }
    }
}

你可能感兴趣的:(shiro+mysql动态验证)