如何在mariaDB中创建为新用户授予数据库访问权限的角色?

时间:2017-11-17 20:59:55

标签: mysql mariadb

创建角色的正确方法是什么,然后将新用户分配给角色以授予对所需数据库的访问权限?

它没有像我预期的那样为我工作。

如果我尝试创建读/写角色和只读角色,然后授予角色权限,然后创建具有默认角色的用户,我会收到用户的数据库访问被拒绝错误:

CREATE DATABASE testDb;

CREATE ROLE readOnly;
CREATE ROLE readWrite;

GRANT SELECT ON testDB . * TO readOnly;
GRANT ALL ON testDB . * TO readWrite;

CREATE USER 'testUser'@'%' IDENTIFIED BY 'testPass';

GRANT readOnly TO testUser;
GRANT readWrite TO testUser;

SET DEFAULT ROLE readOnly FOR testUser;
\q

然后,当我尝试以testUser连接到数据库时:

/mysql -u testUser -p -D testDb
ERROR 1044 (42000): Access denied for user 'testUser'@'%' to database 'testDb'

另一方面,如果我不使用角色并直接向用户授予权限,没有角色的用户,我不会得到数据库访问被拒绝错误:

DROP USER testUser;
DROP ROLE readWrite;
DROP ROLE readOnly;

GRANT ALL ON testDb . * TO testUser@'%' IDENTIFIED BY 'testPass';
\q

现在,以testUser的方式连接:

mysql -u testUser -p -D testDb
Enter password:
MariaDB [testDb]> 

1 个答案:

答案 0 :(得分:1)

我无法重现问题(小心使用数据库对象名称中的大写和小写):

$ mysql -u root -p
Enter password:

MariaDB [(none)]> SELECT VERSION();
+----------------+
| VERSION()      |
+----------------+
| 10.3.2-MariaDB |
+----------------+
1 row in set (0.000 sec)

MariaDB [(none)]> CREATE DATABASE `testDb`;
Query OK, 1 row affected (0.000 sec)

MariaDB [(none)]> CREATE ROLE `readOnly`;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> CREATE ROLE `readWrite`;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> GRANT SELECT ON `testDb`.* TO `readOnly`;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> GRANT ALL ON `testDb`.* TO `readWrite`;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> CREATE USER 'testUser'@'%' IDENTIFIED BY '*********';
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> GRANT `readOnly` TO `testUser`;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> GRANT `readWrite` TO `testUser`;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> SET DEFAULT ROLE `readOnly` FOR `testUser`;
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> \q
Bye

$ mysql -u testUser -p
Enter password:

MariaDB [(none)]> SELECT CURRENT_USER();
+----------------+
| CURRENT_USER() |
+----------------+
| testUser@%     |
+----------------+
1 row in set (0.000 sec)

MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| testDb             |
+--------------------+
2 rows in set (0.001 sec)

MariaDB [(none)]> SELECT CURRENT_ROLE;
+--------------+
| CURRENT_ROLE |
+--------------+
| readOnly     |
+--------------+
1 row in set (0.000 sec)
相关问题