行列权限控制

YMatrix 行列权限控制可使用视图(Views)进行。通过创建视图来限制用户对某些行和某些列的访问。视图可以只包含用户有权访问的行和列,从而隐藏其他敏感行和列。

本节我们将通过一个基本示例进行行级权限控制和列级权限控制的展示。

1. 表的创建

创建测试表,并插入测试数据。

drop table if exists salary cascade;
create table salary (
         id int
        ,name varchar(100)
        ,amount numeric
        ,users varchar
) distributed by (id);

insert into salary values(1,'张三',5000,'mxzz1'),(2,'李四',6000,'mxzz2');

2. 行级权限控制

  • 创建测试用户
drop user mxzz1;
drop user mxzz2;
create user mxzz1 with password '123123';
create user mxzz2 with password '123123';
  • 创建视图
create or replace view user_salary as 
select * from salary
where users = user::varchar(64);
  • 分配权限
grant select on table user_salary to mxzz1;
grant select on table user_salary to mxzz2;
  • 使用 mxzz1 用户进行数据查询
-- 查询测试
psql postgres -h 127.0.0.1 -U mxzz1

-- 仅返回 mxzz1 用户的薪资信息
select * from user_salary;

id | name | amount | users 
---|------|--------|-------
1  | 张三  |  5000  | mxzz1 
  • 使用 mxzz2 用户进行数据查询
-- 查询测试 2
psql postgres -h 127.0.0.1 -U mxzz2

-- 仅返回 mxzz2 用户的薪资信息 
select * from user_salary;

id | name | amount | users 
---|------|--------|-------
2  | 李四  |  6000  | mxzz2

3. 列级权限控制

  • 创建测试用户
drop user lingdao;
drop user commonuser;
create user lingdao with password '123123';
create user commonuser with password '123123';
  • 回收表的public权限
revoke all ON salary from public;
  • 授权列权限
grant select(id,name,users) on table salary to lingdao;
grant select(id,name,amount,users) on table salary to commonuser;
  • 使用 lingdao 用户进行数据查询
psql postgres -h 127.0.0.1 -U lingdao

-- 全表查询失败
select * from salary;
ERROR: penmission denied for table salary

-- 授权列查询成功
select id,name,users from salary;

id | name | users 
---|------|-------
1  | 张三  | mxzz1 
2  | 李四  | mxzz2 
  • 使用 commonuser 用户进行数据查询
psql postgres -h 127.0.0.1 -U commonuser

-- 全表查询成功
select * from salary ;

id | name | amount | users 
---|------|--------|-------
1  | 张三  |  5000  | mxzz1 
2  | 李四  |  6000  | mxzz2