Shiro授权数据的持久化
1. 表结构
2. 角色
-
创建实体Role
public class Role { private int id; private String name; ...
-
在User中设置Role的属性
public class User { private Integer id; private String username; private String password; private String salt; private String role; private List<Role> roles; ...
-
通过username查询对应的Role
public class CustomerRealm extends AuthorizingRealm { @Autowired private UserService userService; /** * 授权 * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { //getUsername String username = (String) principalCollection.getPrimaryPrincipal(); //getRole User user = userService.queryUserRoleByUserName(username); //roles List<Role> roles = user.getRoles(); //SimpleAuthorizationInfo SimpleAuthorizationInfo simpleAuthorizationInfo = null; //添加角色 if (!CollectionUtils.isEmpty(roles)){ //SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); for (Role role: roles) { simpleAuthorizationInfo.addRole(role.getRole()); } } return simpleAuthorizationInfo; }
-
sql
<resultMap id="UserRoleResultMap" type="com.cm.shiro.shirotest.model.User"> <id column="id" jdbcType="BIGINT" property="id" /> <result column="username" jdbcType="VARCHAR" property="username" /> <result column="password" jdbcType="VARCHAR" property="password" /> <result column="salt" jdbcType="VARCHAR" property="salt" /> <result column="role" jdbcType="VARCHAR" property="role" /> <collection property="roles" ofType="com.cm.shiro.shirotest.model.Role" select="selectRole" column="id"> <id column="id" jdbcType="BIGINT" property="id"/> <result column="name" jdbcType="VARCHAR" property="name"/> </collection> </resultMap> <!--通过username主身份信息查询role--> <select id="selectUserRoleByUsername" resultMap="UserRoleResultMap"> select id,username,password,salt from test where username = #{username} </select> <select id="selectRole" resultType="com.cm.shiro.shirotest.model.Role"> select role.id id,role.name name from t_role role join (select roleid from t_role_user where userid = #{id}) roleuser on role.id = roleuser.roleid </select>