在shiro中定义如下的权限,打算测试只能用admin角色,才能操作。后面的语句意思为,authc,被认证过的。roles[admin],必须是admin角色。
/adminAdd authc,roles[admin]
主要的坑是查询时开始只查询了admin的信息,没有做关联查询。导致role为null,后来在mybatis的xml文件中,重新封装了查询结果。得解。
在mybatis的xml文件里,必须自定义map,如下
<resultMap type="cn.taotao.bean.Admin" id="WithRoleResultMap"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column ="password" jdbcType="VARCHAR" property="password"/> <result column="email" jdbcType="VARCHAR" property="email" /> <result column="lockFlag" jdbcType="INTEGER" property="lockFlag"/> <!-- 指定联合查询出的角色role字段的封装 --> <association property="role" javaType="cn.taotao.bean.Role"> <id column="role" property="id"/> <result column="rname" property="name"/> <result column="description" property="description"/> </association> </resultMap>
如果没有关联字段的封装,则查出的类,是null,
SQL语句为
<select id="getAdminByName" resultMap="WithRoleResultMap"> <!-- select * from tbl_admin where name = #{name} --> select a.id ,a.name,a.password,a.email,a.lockFlag,a.role,r.description,r.name rname from tbl_admin a left join tbl_role r on a.role = r.id where a.name=#{name} </select>
这里要注意,Rname,如果重命名了,必须在上面的map里的column字段保持一致。
shiro的授权代码
//授权会被 shiro 回调的方法 @Override protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) { //1. 从 PrincipalCollection 中来获取登录用户的信息 Object principal = principals.getPrimaryPrincipal(); Admin adminByName = adminMapper.getAdminByName(principal.toString()); System.out.println("principal is ======"+principal.toString()); //2. 利用登录的用户的信息来用户当前用户的角色或权限(可能需要查询数据库) //Integer roleid = principal.getRole(); //adminByName.getRole().getName() System.out.println("adminByName.toString() is ==="+adminByName.toString()); Role role = adminByName.getRole(); System.out.println("Role().getname is ==="+role.getName()); Set<String> roles = new HashSet<String>(); roles.add(role.getName()); //3. 创建 SimpleAuthorizationInfo, 并设置其 reles 属性. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles); System.out.println("roles size==== "+ roles.size()); for (String rs : roles) { System.out.println("roles set is ========"+rs); } //4. 返回 SimpleAuthorizationInfo 对象. return info; }