一、先进行用户-角色-权限数据分配
1:在role表中添加2个角色 部门经理(deptMgr) 人事经理(empMgr)
2:给人事经理分配权限:员工的crud权限 。在role_permission表中添加4条数据
3:给用户指派某个角色:给zhangsan指定人事经理这个角色 在user_role表中添加1条数据
二、数据库方式授权
1.在自定义的UserRealm添加2个属性:IRoleDAO IPermissionDAO
注意:同时修改spring-shiro.xml文件中UserRealm定义,注入dao实现类
public class UserRealm extends AuthorizingRealm {
@Setter
private IUserDAO userDAO;
@Setter
private IRoleDAO roleDAO;
@Setter
private IPermissionDAO permissionDAO;
//认证操作
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//从token中获取登录的用户名, 查询数据库返回用户信息
String username = (String) token.getPrincipal();
User user = userDAO.getUserByUsername(username);
if(user == null){
return null;
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(),
ByteSource.Util.bytes(user.getUsername()),
getName());
return info;
}
@Override
public String getName() {
return "UserRealm";
}
//授权操作
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
User user = (User) principals.getPrimaryPrincipal();
List<String> permissions = new ArrayList<String>();
List<String> roles = new ArrayList<>();
if("admin".equals(user.getUsername())){
//拥有所有权限
permissions.add("*:*");
//查询所有角色
roles = roleDAO.getAllRoleSn();
}else{
//根据用户id查询该用户所具有的角色
roles = roleDAO.getRoleSnByUserId(user.getId());
//根据用户id查询该用户所具有的权限
permissions = permissionDAO.getPermissionResourceByUserId(user.getId());
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermissions(permissions);
info.addRoles(roles);
return info;
}
}
其中IRoleDAO(getRoleSnByUserId方法) IPermissionDAO(getPermissionResourceByUserId方法)的sql语句为
// IPermissionDAO中
@Override
public List<String> getPermissionResourceByUserId(Long userId) {
String sql = "select resource from permission where id in(" +
" select permission_id from role_permission where role_id in(" +
" select role_id from user_role where user_id = ?)" +
" );";
try {
return template.query(sql, new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString("resource");
}
}, userId);
}catch (Exception e){
e.printStackTrace();
}
return new ArrayList<>();
}
//IRoleDAO中
@Override
public List<String> getRoleSnByUserId(Long userId) {
String sql = "select sn from role where id in (select role_id from user_role where user_id = ?)";
try {
return template.query(sql, new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString("sn");
}
}, userId);
} catch (Exception e) {
e.printStackTrace();
}
return new ArrayList<>();
}
4:测试
1>先使用zhangsan账号登录查看是否有部门操作权限, 如果没有表示授权成功
2>再使用admin账号登录,查看是否有部门操作权 如果没有表示授权失败