MySQL user and authority management

title: MySQL用户与权限管理
date: 2023-04-04 16:23:47
tags:

1. User Management

1.1 Log in to the MySQL server

After starting the MySQL service, you can log in to the MySQL server through the mysql command. The command is as follows:

mysql –h hostname|hostIP –P port –u username –p DatabaseName –e "SQL语句"

The parameters in the command are described in detail below:

  • The -h parameter is followed by the host name or host IP, where hostname is the host and hostIP is the host IP.

  • The -P parameter is followed by the port of the MySQL service, and the parameter is used to connect to the specified port. The default port of the MySQL service is 3306. If this parameter is not used, it will automatically connect to port 3306, and port is the port number of the connection.

  • The -u parameter is followed by the user name, where username is the user name.

  • The -p parameter will prompt for a password.

  • The DatabaseName parameter indicates which database to log in to. If there is no such parameter, it will directly log in to the MySQL database, and then you can use the USE command to select the database.

  • SQL statements can be added directly after the -e parameter. After logging in to the MySQL server, you can execute this SQL statement, and then exit the MySQL server

Example:

mysql -uroot -p -hlocalhost -P3306 mysql -e "select host,user from user"

1.2 Create user

The basic syntax of the CREATE USER statement is as follows:

CREATE USER 用户名 [IDENTIFIED BY '密码'][,用户名 [IDENTIFIED BY '密码']];

  • The username parameter indicates the account of the newly created user, which is composed of the user (User) and the host name (Host);

  • "[ ]" means optional, that is to say, you can specify that password authentication is required for user login, or you can not specify password authentication, so that users can log in directly. However, the method of not specifying a password is not safe and is not recommended. If you specify a password value, you need to use IDENTIFIED BY to specify the plaintext password value.

  • The CREATE USER statement can create multiple users at the same time.

Example:

CREATE USER zhang3 IDENTIFIED BY '123123'; # 默认host是 %

CREATE USER 'kangshifu'@'localhost' IDENTIFIED BY '123456';

mysql> CREATE USER zhang3 IDENTIFIED BY '123123';
Query OK, 0 rows affected (0.05 sec)

mysql> CREATE USER 'kangshifu'@'localhost' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.01 sec)

mysql> 

1.3 Modify user

Modify username:

UPDATE mysql.user SET USER='li4' WHERE USER='wang5';

FLUSH PRIVILEGES;

mysql> CREATE USER wang5  IDENTIFIED BY '123123'; #
Query OK, 0 rows affected (0.01 sec)

mysql> UPDATE mysql.user SET USER='li4' WHERE USER='wang5';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

mysql> 

1.4 Delete user

Method 1: Use DROP to delete (recommended)

When using the DROP USER statement to delete a user, the DROP USER authority must be used. The basic syntax of the DROP USER statement is as follows:

DROP USER user[,user]…;

Example:

DROP USER li4 ; # 默认删除host为%的用户

DROP USER 'kangshifu'@'localhost';

Method 2: Use DELETE to delete

DELETE FROM mysql.user WHERE Host=’hostname’ AND User=’username’;

After executing the DELETE command, use the FLUSH command to make the user effective. The command is as follows:

FLUSH PRIVILEGES;

Example:

DELETE FROM mysql.user WHERE Host='localhost' AND User='Emily';

FLUSH PRIVILEGES;

  • Note: It is not recommended to delete via DELETE FROM USER u WHERE USER='li4', the system will retain residual information. The drop user command will delete the user and the corresponding permissions. After executing the command, you will find that the corresponding records in the mysql.user table and the mysql.db table have disappeared.

1.5 Set current user password

The old way of writing is as follows:

# 修改当前用户的密码:(MySQL5.7测试有效)
SET PASSWORD = PASSWORD('123456');

Here is the recommended way to write:

1. Use the ALTER USER command to modify the current user password. Users can use the ALTER command to modify their own password. The following statement represents modifying the password of the current login user. The basic syntax is as follows:

ALTER USER USER() IDENTIFIED BY 'new_password';

2. Use the SET statement to modify the current user password. After logging in to MySQL as the root user, you can use the SET statement to modify the password. The specific SQL statement is as follows:

SET PASSWORD='new_password';

This statement will automatically encrypt the password and assign it to the current user.

1.6 Modify other user passwords

1. Use the ALTER statement to modify the password of an ordinary user You can use the ALTER USER statement to modify the password of an ordinary user. The basic syntax is as follows:

ALTER USER user [IDENTIFIED BY 'new password']

[,user[IDENTIFIED BY 'new password']]…;

2. Use the SET command to modify the password of an ordinary user After logging in to the MySQL server with the root user, you can use the SET statement to modify the password of an ordinary user. The code for the SET statement is as follows:

SET PASSWORD FOR 'username'@'hostname'='new_password';

3. Use the UPDATE statement to modify the password of ordinary users (not recommended)

UPDATE MySQL.user SET authentication_string=PASSWORD("123456")

WHERE User = "username" AND Host = "hostname";


1.7 MySQL8 password management (understand)

  • Password Expiration Policy

In MySQL, the database administrator can manually set account password expiration, or establish an automatic password expiration policy.

The expiration policy can be global, or a separate expiration policy can be set for each account.

  • Password Reuse Policy

2. Authority management

2.1 Permission List

What permissions does MySQL have?mysql> show privileges;

mysql>  show privileges;
+----------------------------+---------------------------------------+-------------------------------------------------------+
| Privilege                  | Context                               | Comment                                               |
+----------------------------+---------------------------------------+-------------------------------------------------------+
| Alter                      | Tables                                | To alter the table                                    |
| Alter routine              | Functions,Procedures                  | To alter or drop stored functions/procedures          |
| Create                     | Databases,Tables,Indexes              | To create new databases and tables                    |
| Create routine             | Databases                             | To use CREATE FUNCTION/PROCEDURE                      |
| Create role                | Server Admin                          | To create new roles                                   |
| Create temporary tables    | Databases                             | To use CREATE TEMPORARY TABLE                         |
| Create view                | Tables                                | To create new views                                   |
| Create user                | Server Admin                          | To create new users                                   |
| Delete                     | Tables                                | To delete existing rows                               |
| Drop                       | Databases,Tables                      | To drop databases, tables, and views                  |
| Drop role                  | Server Admin                          | To drop roles                                         |
| Event                      | Server Admin                          | To create, alter, drop and execute events             |
| Execute                    | Functions,Procedures                  | To execute stored routines                            |
| File                       | File access on server                 | To read and write files on the server                 |
| Grant option               | Databases,Tables,Functions,Procedures | To give to other users those privileges you possess   |
| Index                      | Tables                                | To create or drop indexes                             |
| Insert                     | Tables                                | To insert data into tables                            |
| Lock tables                | Databases                             | To use LOCK TABLES (together with SELECT privilege)   |
| Process                    | Server Admin                          | To view the plain text of currently executing queries |
| Proxy                      | Server Admin                          | To make proxy user possible                           |
| References                 | Databases,Tables                      | To have references on tables                          |
| Reload                     | Server Admin                          | To reload or refresh tables, logs and privileges      |
| Replication client         | Server Admin                          | To ask where the slave or master servers are          |
| Replication slave          | Server Admin                          | To read binary log events from the master             |
| Select                     | Tables                                | To retrieve rows from table                           |
| Show databases             | Server Admin                          | To see all databases with SHOW DATABASES              |
| Show view                  | Tables                                | To see views with SHOW CREATE VIEW                    |
| Shutdown                   | Server Admin                          | To shut down the server                               |
| Super                      | Server Admin                          | To use KILL thread, SET GLOBAL, CHANGE MASTER, etc.   |
| Trigger                    | Tables                                | To use triggers                                       |
| Create tablespace          | Server Admin                          | To create/alter/drop tablespaces                      |
| Update                     | Tables                                | To update existing rows                               |
| Usage                      | Server Admin                          | No privileges - allow connect only                    |
| XA_RECOVER_ADMIN           | Server Admin                          |                                                       |
| SHOW_ROUTINE               | Server Admin                          |                                                       |
| SET_USER_ID                | Server Admin                          |                                                       |
| RESOURCE_GROUP_USER        | Server Admin                          |                                                       |
| APPLICATION_PASSWORD_ADMIN | Server Admin                          |                                                       |
| SYSTEM_VARIABLES_ADMIN     | Server Admin                          |                                                       |
| AUDIT_ADMIN                | Server Admin                          |                                                       |
| SERVICE_CONNECTION_ADMIN   | Server Admin                          |                                                       |
| CLONE_ADMIN                | Server Admin                          |                                                       |
| PERSIST_RO_VARIABLES_ADMIN | Server Admin                          |                                                       |
| FLUSH_USER_RESOURCES       | Server Admin                          |                                                       |
| BINLOG_ADMIN               | Server Admin                          |                                                       |
| ROLE_ADMIN                 | Server Admin                          |                                                       |
| SESSION_VARIABLES_ADMIN    | Server Admin                          |                                                       |
| BINLOG_ENCRYPTION_ADMIN    | Server Admin                          |                                                       |
| FLUSH_STATUS               | Server Admin                          |                                                       |
| SYSTEM_USER                | Server Admin                          |                                                       |
| ENCRYPTION_KEY_ADMIN       | Server Admin                          |                                                       |
| REPLICATION_SLAVE_ADMIN    | Server Admin                          |                                                       |
| GROUP_REPLICATION_ADMIN    | Server Admin                          |                                                       |
| BACKUP_ADMIN               | Server Admin                          |                                                       |
| RESOURCE_GROUP_ADMIN       | Server Admin                          |                                                       |
| FLUSH_OPTIMIZER_COSTS      | Server Admin                          |                                                       |
| TABLE_ENCRYPTION_ADMIN     | Server Admin                          |                                                       |
| FLUSH_TABLES               | Server Admin                          |                                                       |
| CONNECTION_ADMIN           | Server Admin                          |                                                       |
| INNODB_REDO_LOG_ENABLE     | Server Admin                          |                                                       |
| INNODB_REDO_LOG_ARCHIVE    | Server Admin                          |                                                       |
| REPLICATION_APPLIER        | Server Admin                          |                                                       |
+----------------------------+---------------------------------------+-------------------------------------------------------+
62 rows in set (0.00 sec)

mysql> 

(1) CREATE and DROP permissions, you can create new databases and tables, or delete (remove) existing databases and tables. If the DROP permission in the MySQL database is granted to a user, the user can delete the database in which the MySQL access permission is saved.

(2) SELECT, INSERT, UPDATE, and DELETE permissions allow operations to be performed on existing tables in a database. (3) SELECT privileges are only used when they actually retrieve rows from a table.

(4) The INDEX permission allows creating or deleting indexes, and INDEX applies to existing tables. If you have CREATE privilege on a table, you can include index definitions in the CREATE TABLE statement.

(5) ALTER permission can use ALTER TABLE to change the structure of the table and rename the table.

(6) CREATE ROUTINE permission is used to create saved programs (functions and programs), ALTER ROUTINE permission is used to change and delete saved programs, and EXECUTE permission is used to execute saved programs.

(7) GRANT permission allows authorization to other users, which can be used for databases, tables and saved programs.

(8) FILE permission enables users to use LOAD DATA INFILE and SELECT ... INTO OUTFILE statements to read or write files on the server, and any user granted FILE permission can read or write any file on the MySQL server (indicating that users can Read any files in the database directory, because the server can access these files).

2.2 Principles of Granting Permissions

Privilege control is mainly for security reasons, so the following rules of thumb need to be followed:

1. Only the minimum permissions that can meet the needs are granted to prevent users from doing bad things. For example, if the user only needs to query, then only the select permission is sufficient, and do not give the user the update, insert or delete permission.

2. When creating a user, restrict the user's login host, generally to the specified IP or intranet IP segment.

3. Set a password that satisfies the complexity of the password for each user.

4. Regularly clean up unnecessary users, reclaim permissions or delete users.

2.3 Granting Permissions

There are two ways to authorize users, which are granting roles to users to authorize users and directly authorizing users. The user is the user of the database. We can control the user's access to the database and eliminate security risks by granting the user permission to access resources in the database.

Authorization command:

GRANT 权限1,权限2,…权限n ON 数据库名称.表名称 TO 用户名@用户地址 [IDENTIFIED BY ‘密码口令’];

  • If the user is found to have no such permission, a new user will be created directly.

for example:

  • Give the li4 user the permission to insert, delete, modify and check all tables under the atguigudb library by using the local command line.

GRANT SELECT,INSERT,DELETE,UPDATE ON atguigudb.* TO li4@localhost ;

  • Grant user joe who logs in through the network all permissions to all tables in all databases, and set the password to 123. Note that only grant permissions are not included here

GRANT ALL PRIVILEGES ON *.* TO joe@'%' IDENTIFIED BY '123';

When we develop applications, we often encounter a need to group data horizontally and vertically according to different users.

  • The so-called horizontal grouping refers to the range of data that users can access, such as which table data can be seen;

  • The so-called vertical grouping refers to the extent to which users can access the data they come into contact with, such as viewing, modifying, or even deleting.


2.4 View permissions

  • View current user permissions
SHOW GRANTS;
# 或
SHOW GRANTS FOR CURRENT_USER;
# 或
SHOW GRANTS FOR CURRENT_USER();
mysql> SHOW GRANTS;
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@%                                                                                                                                                                                                                                                                                                                                                                                |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE, CREATE ROLE, DROP ROLE ON *.* TO `root`@`%` WITH GRANT OPTION |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> 
  • View a user's global permissions
SHOW GRANTS FOR 'user'@'主机地址' ;

2.5 Withdraw authority

Withdrawing permissions means canceling certain permissions that have been granted to the user. Taking back unnecessary permissions from users can guarantee the security of the system to a certain extent. Use in MySQL REVOKE语句to cancel certain privileges of users. After using REVOKE to revoke the authority, the user account records will be deleted from the db, host, tables_priv and columns_priv tables, but the user account records are still saved in the user table (use the DROP USER statement to delete the account records in the user table).

Note: Before deleting a user account from the user table, all privileges of the corresponding user should be revoked.

  • revoke authority command

REVOKE 权限1,权限2,…权限n ON 数据库名称.表名称 FROM 用户名@用户地址;

  • example
#收回全库全表的所有权限
REVOKE ALL PRIVILEGES ON *.* FROM joe@'%';
#收回mysql库下的所有表的插删改查权限
REVOKE SELECT,INSERT,UPDATE,DELETE ON mysql.* FROM joe@localhost;
  • Note: the user must log in again to take effect

3. Permission table

3.1 user table

The user table is the most important permission table in MySQL, 记录用户账号和权限信息with 49 fields. These fields can be divided into 4 categories, namely scope column (or user column), permission column, security column and resource control column.

1. Range column (or user column)

host : Indicates the connection type

   % means all remote connections via TCP

    IP address such as (192.168.1.2, 127.0.0.1) TCP connection through specifying ip address

    Machine name TCP mode connection by specifying the machine name in the network

    ::1 The local ip address of IPv6, which is equivalent to 127.0.0.1 of IPv4

    localhost Local connection via command line, such as mysql -u xxx -p xxx connection.

user : Indicates the user name, and the permissions of the same user linked in different ways are different.

password : password

  • All password strings are ciphertext strings generated by password (plaintext string). MySQL 8.0 adds role management in user management, and the default password encryption method has also been SHA1adjusted SHA2irreversible. At the same time, with the functions of disabling users and user expiration in MySQL 5.7, the functions and security of MySQL in user management have been greatly enhanced compared with the previous version.

  • The password field of mysql 5.7 and later versions is no longer used when the password is saved in authentication_stringthe field .

2. Permission column

  • Grant_priv field

Indicates whether you have GRANT authority

  • Shutdown_priv field

Indicates whether you have the permission to stop the MySQL service

  • Super_priv field

Indicates whether you have super authority

  • Execute_priv field

Indicates whether you have EXECUTE permission. With EXECUTE permission, you can execute stored procedures and functions.

  • Select_priv , Insert_priv etc

Permissions owned by this user.

3. Security column The security column has only 6 fields, two of which are related to ssl (ssl_type, ssl_cipher), used for; two 加密are related to x509 (x509_issuer, x509_subject), used for 标识用户; the other two Plugin fields are used 验证用户身份for Plugin, this field cannot be empty. If this field is empty, the server uses the built-in authentication mechanism to authenticate the user.

4. Resource control column The fields in the resource control column are used 限制用户使用的资源to contain 4 fields, which are:

①max_questions, the number of query operations allowed by the user per hour; ②max_updates, the updates allowed by the user per hour

Number of operations; ③max_connections, the number of connection operations the user is allowed to perform per hour; ④max_user_connections, the user

The number of simultaneous connections allowed.

View fields:

DESC mysql.user;

mysql> DESC mysql.user;
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field                    | Type                              | Null | Key | Default               | Extra |
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host                     | char(255)                         | NO   | PRI |                       |       |
| User                     | char(32)                          | NO   | PRI |                       |       |
| Select_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Insert_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Update_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Delete_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Create_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Drop_priv                | enum('N','Y')                     | NO   |     | N                     |       |
| Reload_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Shutdown_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Process_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| File_priv                | enum('N','Y')                     | NO   |     | N                     |       |
| Grant_priv               | enum('N','Y')                     | NO   |     | N                     |       |
| References_priv          | enum('N','Y')                     | NO   |     | N                     |       |
| Index_priv               | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_priv               | enum('N','Y')                     | NO   |     | N                     |       |
| Show_db_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Super_priv               | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tmp_table_priv    | enum('N','Y')                     | NO   |     | N                     |       |
| Lock_tables_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Execute_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_slave_priv          | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_client_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Create_view_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Show_view_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Create_routine_priv      | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_routine_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Create_user_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Event_priv               | enum('N','Y')                     | NO   |     | N                     |       |
| Trigger_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tablespace_priv   | enum('N','Y')                     | NO   |     | N                     |       |
| ssl_type                 | enum('','ANY','X509','SPECIFIED') | NO   |     |                       |       |
| ssl_cipher               | blob                              | NO   |     | NULL                  |       |
| x509_issuer              | blob                              | NO   |     | NULL                  |       |
| x509_subject             | blob                              | NO   |     | NULL                  |       |
| max_questions            | int unsigned                      | NO   |     | 0                     |       |
| max_updates              | int unsigned                      | NO   |     | 0                     |       |
| max_connections          | int unsigned                      | NO   |     | 0                     |       |
| max_user_connections     | int unsigned                      | NO   |     | 0                     |       |
| plugin                   | char(64)                          | NO   |     | caching_sha2_password |       |
| authentication_string    | text                              | YES  |     | NULL                  |       |
| password_expired         | enum('N','Y')                     | NO   |     | N                     |       |
| password_last_changed    | timestamp                         | YES  |     | NULL                  |       |
| password_lifetime        | smallint unsigned                 | YES  |     | NULL                  |       |
| account_locked           | enum('N','Y')                     | NO   |     | N                     |       |
| Create_role_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Drop_role_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Password_reuse_history   | smallint unsigned                 | YES  |     | NULL                  |       |
| Password_reuse_time      | smallint unsigned                 | YES  |     | NULL                  |       |
| Password_require_current | enum('N','Y')                     | YES  |     | NULL                  |       |
| User_attributes          | json                              | YES  |     | NULL                  |       |
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
51 rows in set (0.11 sec)

mysql> 

To view users, display data in columns:

SELECT * FROM mysql.user \G;

mysql> SELECT * FROM mysql.user \G;
*************************** 1. row ***************************
                    Host: %
                    User: root
             Select_priv: Y
             Insert_priv: Y
             Update_priv: Y
             Delete_priv: Y
             Create_priv: Y
               Drop_priv: Y
             Reload_priv: Y
           Shutdown_priv: Y
            Process_priv: Y
               File_priv: Y
              Grant_priv: Y
         References_priv: Y
              Index_priv: Y
              Alter_priv: Y
            Show_db_priv: Y
              Super_priv: Y
   Create_tmp_table_priv: Y
        Lock_tables_priv: Y
            Execute_priv: Y
         Repl_slave_priv: Y
        Repl_client_priv: Y
        Create_view_priv: Y
          Show_view_priv: Y
     Create_routine_priv: Y
      Alter_routine_priv: Y
        Create_user_priv: Y
              Event_priv: Y
            Trigger_priv: Y
  Create_tablespace_priv: Y
                ssl_type: 
              ssl_cipher: NULL
             x509_issuer: NULL
            x509_subject: NULL
           max_questions: 0
             max_updates: 0
         max_connections: 0
    max_user_connections: 0
                  plugin: mysql_native_password
   authentication_string: *6691484EA6B50DDDE1926A220DA01FA9E575C18A
        password_expired: N
   password_last_changed: 2023-04-03 08:20:38
       password_lifetime: NULL
          account_locked: N
        Create_role_priv: Y
          Drop_role_priv: Y
  Password_reuse_history: NULL
     Password_reuse_time: NULL
Password_require_current: NULL
         User_attributes: NULL
*************************** 2. row ***************************
                    Host: %
                    User: zhang3
             Select_priv: N
             Insert_priv: N
             Update_priv: N
             Delete_priv: N
             Create_priv: N
               Drop_priv: N
             Reload_priv: N
           Shutdown_priv: N
            Process_priv: N
               File_priv: N
              Grant_priv: N
         References_priv: N
              Index_priv: N
              Alter_priv: N
            Show_db_priv: N
              Super_priv: N
   Create_tmp_table_priv: N
        Lock_tables_priv: N
            Execute_priv: N
         Repl_slave_priv: N
        Repl_client_priv: N
        Create_view_priv: N
          Show_view_priv: N
     Create_routine_priv: N
      Alter_routine_priv: N
        Create_user_priv: N
              Event_priv: N
            Trigger_priv: N
  Create_tablespace_priv: N
                ssl_type: 
              ssl_cipher: NULL
             x509_issuer: NULL
            x509_subject: NULL
           max_questions: 0
             max_updates: 0
         max_connections: 0
    max_user_connections: 0
                  plugin: caching_sha2_password
   authentication_string: $A$005$yb_vf    96"E LS'un1=0GsUNgaAjqRpLNW1vKWOpeXWieRGJVMXpPPbTyWmXg4
        password_expired: N
   password_last_changed: 2023-04-04 01:27:49
       password_lifetime: NULL
          account_locked: N
        Create_role_priv: N
          Drop_role_priv: N
  Password_reuse_history: NULL
     Password_reuse_time: NULL
Password_require_current: NULL
         User_attributes: NULL
*************************** 3. row ***************************
                    Host: localhost
                    User: mysql.infoschema
             Select_priv: Y
             Insert_priv: N
             Update_priv: N
             Delete_priv: N
             Create_priv: N
               Drop_priv: N
             Reload_priv: N
           Shutdown_priv: N
            Process_priv: N
               File_priv: N
              Grant_priv: N
         References_priv: N
              Index_priv: N
              Alter_priv: N
            Show_db_priv: N
              Super_priv: N
   Create_tmp_table_priv: N
        Lock_tables_priv: N
            Execute_priv: N
         Repl_slave_priv: N
        Repl_client_priv: N
        Create_view_priv: N
          Show_view_priv: N
     Create_routine_priv: N
      Alter_routine_priv: N
        Create_user_priv: N
              Event_priv: N
            Trigger_priv: N
  Create_tablespace_priv: N
                ssl_type: 
              ssl_cipher: NULL
             x509_issuer: NULL
            x509_subject: NULL
           max_questions: 0
             max_updates: 0
         max_connections: 0
    max_user_connections: 0
                  plugin: caching_sha2_password
   authentication_string: $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED
        password_expired: N
   password_last_changed: 2023-04-03 07:52:40
       password_lifetime: NULL
          account_locked: Y
        Create_role_priv: N
          Drop_role_priv: N
  Password_reuse_history: NULL
     Password_reuse_time: NULL
Password_require_current: NULL
         User_attributes: NULL
*************************** 4. row ***************************
                    Host: localhost
                    User: mysql.session
             Select_priv: N
             Insert_priv: N
             Update_priv: N
             Delete_priv: N
             Create_priv: N
               Drop_priv: N
             Reload_priv: N
           Shutdown_priv: Y
            Process_priv: N
               File_priv: N
              Grant_priv: N
         References_priv: N
              Index_priv: N
              Alter_priv: N
            Show_db_priv: N
              Super_priv: Y
   Create_tmp_table_priv: N
        Lock_tables_priv: N
            Execute_priv: N
         Repl_slave_priv: N
        Repl_client_priv: N
        Create_view_priv: N
          Show_view_priv: N
     Create_routine_priv: N
      Alter_routine_priv: N
        Create_user_priv: N
              Event_priv: N
            Trigger_priv: N
  Create_tablespace_priv: N
                ssl_type: 
              ssl_cipher: NULL
             x509_issuer: NULL
            x509_subject: NULL
           max_questions: 0
             max_updates: 0
         max_connections: 0
    max_user_connections: 0
                  plugin: caching_sha2_password
   authentication_string: $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED
        password_expired: N
   password_last_changed: 2023-04-03 07:52:40
       password_lifetime: NULL
          account_locked: Y
        Create_role_priv: N
          Drop_role_priv: N
  Password_reuse_history: NULL
     Password_reuse_time: NULL
Password_require_current: NULL
         User_attributes: NULL
*************************** 5. row ***************************
                    Host: localhost
                    User: mysql.sys
             Select_priv: N
             Insert_priv: N
             Update_priv: N
             Delete_priv: N
             Create_priv: N
               Drop_priv: N
             Reload_priv: N
           Shutdown_priv: N
            Process_priv: N
               File_priv: N
              Grant_priv: N
         References_priv: N
              Index_priv: N
              Alter_priv: N
            Show_db_priv: N
              Super_priv: N
   Create_tmp_table_priv: N
        Lock_tables_priv: N
            Execute_priv: N
         Repl_slave_priv: N
        Repl_client_priv: N
        Create_view_priv: N
          Show_view_priv: N
     Create_routine_priv: N
      Alter_routine_priv: N
        Create_user_priv: N
              Event_priv: N
            Trigger_priv: N
  Create_tablespace_priv: N
                ssl_type: 
              ssl_cipher: NULL
             x509_issuer: NULL
            x509_subject: NULL
           max_questions: 0
             max_updates: 0
         max_connections: 0
    max_user_connections: 0
                  plugin: caching_sha2_password
   authentication_string: $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED
        password_expired: N
   password_last_changed: 2023-04-03 07:52:40
       password_lifetime: NULL
          account_locked: Y
        Create_role_priv: N
          Drop_role_priv: N
  Password_reuse_history: NULL
     Password_reuse_time: NULL
Password_require_current: NULL
         User_attributes: NULL
5 rows in set (0.01 sec)

ERROR: 
No query specified

mysql> 

Query specific fields:

SELECT host,user,authentication_string,select_priv,insert_priv,drop_priv

FROM mysql.user;

mysql> SELECT host,user,authentication_string,select_priv,insert_priv,drop_priv
    -> FROM mysql.user;
+-----------+------------------+------------------------------------------------------------------------+-------------+-------------+-----------+
| host      | user             | authentication_string                                                  | select_priv | insert_priv | drop_priv |
+-----------+------------------+------------------------------------------------------------------------+-------------+-------------+-----------+
| %         | root             | *6691484EA6B50DDDE1926A220DA01FA9E575C18A                              | Y           | Y           | Y         |
| %         | zhang3           | $A$005$yb_vf    96"E LS'un1=0GsUNgaAjqRpLNW1vKWOpeXWieRGJVMXpPPbTyWmXg4 | N           | N           | N         |
| localhost | mysql.infoschema | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | Y           | N           | N         |
| localhost | mysql.session    | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | N           | N           | N         |
| localhost | mysql.sys        | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | N           | N           | N         |
+-----------+------------------+------------------------------------------------------------------------+-------------+-------------+-----------+
5 rows in set (0.02 sec)

mysql> 

3.2 db table

Use DESCRIBE to view the basic structure of the db table:

DESCRIBE mysql.db;

1. User column The user column in the db table has 3 fields, namely Host, User, and Db. These 3 fields represent host name, user name and database name respectively. Indicates the operation authority of a user connected to a certain database from a certain host, and the combination of these three fields constitutes the primary key of the db table.

2. Permission column

The two fields Create_routine_priv and Alter_routine_priv determine whether the user has the authority to create and modify stored procedures.

mysql> DESCRIBE mysql.db;
+-----------------------+---------------+------+-----+---------+-------+
| Field                 | Type          | Null | Key | Default | Extra |
+-----------------------+---------------+------+-----+---------+-------+
| Host                  | char(255)     | NO   | PRI |         |       |
| Db                    | char(64)      | NO   | PRI |         |       |
| User                  | char(32)      | NO   | PRI |         |       |
| Select_priv           | enum('N','Y') | NO   |     | N       |       |
| Insert_priv           | enum('N','Y') | NO   |     | N       |       |
| Update_priv           | enum('N','Y') | NO   |     | N       |       |
| Delete_priv           | enum('N','Y') | NO   |     | N       |       |
| Create_priv           | enum('N','Y') | NO   |     | N       |       |
| Drop_priv             | enum('N','Y') | NO   |     | N       |       |
| Grant_priv            | enum('N','Y') | NO   |     | N       |       |
| References_priv       | enum('N','Y') | NO   |     | N       |       |
| Index_priv            | enum('N','Y') | NO   |     | N       |       |
| Alter_priv            | enum('N','Y') | NO   |     | N       |       |
| Create_tmp_table_priv | enum('N','Y') | NO   |     | N       |       |
| Lock_tables_priv      | enum('N','Y') | NO   |     | N       |       |
| Create_view_priv      | enum('N','Y') | NO   |     | N       |       |
| Show_view_priv        | enum('N','Y') | NO   |     | N       |       |
| Create_routine_priv   | enum('N','Y') | NO   |     | N       |       |
| Alter_routine_priv    | enum('N','Y') | NO   |     | N       |       |
| Execute_priv          | enum('N','Y') | NO   |     | N       |       |
| Event_priv            | enum('N','Y') | NO   |     | N       |       |
| Trigger_priv          | enum('N','Y') | NO   |     | N       |       |
+-----------------------+---------------+------+-----+---------+-------+
22 rows in set (0.01 sec)

mysql> 

3.3 tables_priv table and columns_priv table

The tables_priv table is used to set the operation permission on the table, and the columns_priv table is used to set the permission on a certain column of the table. tables_priv table and

The structure of the columns_priv table is shown in the figure:

desc mysql.tables_priv;

mysql> desc mysql.tables_priv;
+-------------+-----------------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-----------------------------------------------+
| Field       | Type                                                                                                                              | Null | Key | Default           | Extra                                         |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-----------------------------------------------+
| Host        | char(255)                                                                                                                         | NO   | PRI |                   |                                               |
| Db          | char(64)                                                                                                                          | NO   | PRI |                   |                                               |
| User        | char(32)                                                                                                                          | NO   | PRI |                   |                                               |
| Table_name  | char(64)                                                                                                                          | NO   | PRI |                   |                                               |
| Grantor     | varchar(288)                                                                                                                      | NO   | MUL |                   |                                               |
| Timestamp   | timestamp                                                                                                                         | NO   |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED on update CURRENT_TIMESTAMP |
| Table_priv  | set('Select','Insert','Update','Delete','Create','Drop','Grant','References','Index','Alter','Create View','Show view','Trigger') | NO   |     |                   |                                               |
| Column_priv | set('Select','Insert','Update','References')                                                                                      | NO   |     |                   |                                               |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-----------------------------------------------+
8 rows in set (0.00 sec)

mysql> 

The tables_priv table has 8 fields, namely Host, Db, User, Table_name, Grantor, Timestamp, Table_priv, and Column_priv. Each field is described as follows:

  • The four fields Host, Db, User and Table_name represent the host name, database name, user name and table name respectively.

  • Grantor represents the user who modified the record.

  • Timestamp indicates the time when the record was modified.

  • Table_priv represents the operation authority of the object. Including Select, Insert, Update, Delete, Create, Drop, Grant, References, Index and Alter.

  • The Column_priv field indicates the operation permission on the columns in the table, including Select, Insert, Update and References.

desc mysql.columns_priv;

mysql> desc mysql.columns_priv;
+-------------+----------------------------------------------+------+-----+-------------------+-----------------------------------------------+
| Field       | Type                                         | Null | Key | Default           | Extra                                         |
+-------------+----------------------------------------------+------+-----+-------------------+-----------------------------------------------+
| Host        | char(255)                                    | NO   | PRI |                   |                                               |
| Db          | char(64)                                     | NO   | PRI |                   |                                               |
| User        | char(32)                                     | NO   | PRI |                   |                                               |
| Table_name  | char(64)                                     | NO   | PRI |                   |                                               |
| Column_name | char(64)                                     | NO   | PRI |                   |                                               |
| Timestamp   | timestamp                                    | NO   |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED on update CURRENT_TIMESTAMP |
| Column_priv | set('Select','Insert','Update','References') | NO   |     |                   |                                               |
+-------------+----------------------------------------------+------+-----+-------------------+-----------------------------------------------+
7 rows in set (0.00 sec)

mysql> 

3.4 procs_priv

The procs_priv table can set operation permissions for stored procedures and stored functions. The table structure is shown in the figure:

desc mysql.procs_priv;

mysql> desc mysql.procs_priv;
+--------------+----------------------------------------+------+-----+-------------------+-----------------------------------------------+
| Field        | Type                                   | Null | Key | Default           | Extra                                         |
+--------------+----------------------------------------+------+-----+-------------------+-----------------------------------------------+
| Host         | char(255)                              | NO   | PRI |                   |                                               |
| Db           | char(64)                               | NO   | PRI |                   |                                               |
| User         | char(32)                               | NO   | PRI |                   |                                               |
| Routine_name | char(64)                               | NO   | PRI |                   |                                               |
| Routine_type | enum('FUNCTION','PROCEDURE')           | NO   | PRI | NULL              |                                               |
| Grantor      | varchar(288)                           | NO   | MUL |                   |                                               |
| Proc_priv    | set('Execute','Alter Routine','Grant') | NO   |     |                   |                                               |
| Timestamp    | timestamp                              | NO   |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED on update CURRENT_TIMESTAMP |
+--------------+----------------------------------------+------+-----+-------------------+-----------------------------------------------+
8 rows in set (0.00 sec)

mysql> 

4. Access control (understand)

4.1 Connection Verification Phase

When a user tries to connect to the MySQL server, the server accepts or rejects the connection based on the user's identity and whether the user can provide the correct password for authentication. That is, the client user will provide the user name, host address, and user password in the connection request. After receiving the user request, the MySQL server will use the three fields of host, user, and authentication_string in the user table to match the information provided by the client.

The server only accepts the connection if the Host and User fields of the user table record match the client hostname and username, and the correct password is provided. If the connection verification fails, the server completely denies access; otherwise, the server accepts the connection, and then enters phase 2 to wait for user requests.

4.2 Request Verification Phase

Once the connection is established, the server enters phase 2 of access control, which is the request verification phase. With every request that comes in on this connection, the server checks what the request is going to do and whether it has sufficient permissions to do it, which is where the permissions column in the grant table comes into play. These privileges can come from the user, db, table_priv and column_priv tables.

When confirming permissions, MySQL first checks the user table . If the specified permissions are not granted in the user table, MySQL will continue to check the db table. The db table is the next security level, and the permissions are limited to the database level. At this level The SELECT privilege allows the user to view the data in all tables of the specified database; if no restricted privilege is found at this level, MySQL continues to check table and columns_priv table , if all privilege tables have been checked, but still no permitted privileges are found operation, MySQL will return an error message , the operation requested by the user cannot be performed, and the operation fails

Tip: MySQL checks the privilege table in descending order (from the user table to the columns_priv table), but not all privileges perform this process. For example, a user only performs management operations on MySQL after logging in to the MySQL server. At this time, only management rights are involved, so MySQL only checks the user table. In addition, if the requested permission operation is not allowed, MySQL will not continue to check the next level of the table.


5. Role management

5.1 Understanding of roles

The purpose of introducing roles is to facilitate the management of users with the same permissions. Proper permission setting can ensure the security of data, which is very important.

5.2 Create roles

Create a role using the CREATE ROLE statement, the syntax is as follows:

CREATE ROLE 'role_name'[@'host_name'] [,'role_name'[@'host_name']]...

The naming rules for role names are similar to user names. If host_name is omitted, it defaults to %, and role_name cannot be omitted or empty.

Exercise: We now need to create a manager role, we can use the following code:

CREATE ROLE 'manager'@'localhost';

mysql> CREATE ROLE 'manager'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> 
mysql> CREATE ROLE 're0'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> 

5.3 Grant permissions to roles

After the role is created, the role does not have any permissions by default, and we need to authorize the role. The grammatical structure for granting authorization to a role is:GRANT privileges ON table_name TO 'role_name'[@'host_name'];

In the above statement, privileges represents the name of the privilege, and multiple privileges are separated by commas. You can use the SHOW statement to query the permission name, and Figure 11-43 lists some permission lists.

SHOW PRIVILEGES\G;

mysql> SHOW PRIVILEGES\G;
*************************** 1. row ***************************
Privilege: Alter
  Context: Tables
  Comment: To alter the table
*************************** 2. row ***************************
Privilege: Alter routine
  Context: Functions,Procedures
  Comment: To alter or drop stored functions/procedures
*************************** 3. row ***************************
Privilege: Create
  Context: Databases,Tables,Indexes
  Comment: To create new databases and tables
*************************** 4. row ***************************
Privilege: Create routine
  Context: Databases
  Comment: To use CREATE FUNCTION/PROCEDURE
*************************** 5. row ***************************
Privilege: Create role
  Context: Server Admin
  Comment: To create new roles
*************************** 6. row ***************************
Privilege: Create temporary tables
  Context: Databases
  Comment: To use CREATE TEMPORARY TABLE
*************************** 7. row ***************************
Privilege: Create view
  Context: Tables
  Comment: To create new views
*************************** 8. row ***************************
Privilege: Create user
  Context: Server Admin
  Comment: To create new users
*************************** 9. row ***************************
Privilege: Delete
  Context: Tables
  Comment: To delete existing rows
*************************** 10. row ***************************
Privilege: Drop
  Context: Databases,Tables
  Comment: To drop databases, tables, and views
*************************** 11. row ***************************
Privilege: Drop role
  Context: Server Admin
  Comment: To drop roles
*************************** 12. row ***************************
Privilege: Event
  Context: Server Admin
  Comment: To create, alter, drop and execute events
*************************** 13. row ***************************
Privilege: Execute
  Context: Functions,Procedures
  Comment: To execute stored routines
*************************** 14. row ***************************
Privilege: File
  Context: File access on server
  Comment: To read and write files on the server
*************************** 15. row ***************************
Privilege: Grant option
  Context: Databases,Tables,Functions,Procedures
  Comment: To give to other users those privileges you possess
*************************** 16. row ***************************
Privilege: Index
  Context: Tables
  Comment: To create or drop indexes
*************************** 17. row ***************************
Privilege: Insert
  Context: Tables
  Comment: To insert data into tables
*************************** 18. row ***************************
Privilege: Lock tables
  Context: Databases
  Comment: To use LOCK TABLES (together with SELECT privilege)
*************************** 19. row ***************************
Privilege: Process
  Context: Server Admin
  Comment: To view the plain text of currently executing queries
*************************** 20. row ***************************
Privilege: Proxy
  Context: Server Admin
  Comment: To make proxy user possible
*************************** 21. row ***************************
Privilege: References
  Context: Databases,Tables
  Comment: To have references on tables
*************************** 22. row ***************************
Privilege: Reload
  Context: Server Admin
  Comment: To reload or refresh tables, logs and privileges
*************************** 23. row ***************************
Privilege: Replication client
  Context: Server Admin
  Comment: To ask where the slave or master servers are
*************************** 24. row ***************************
Privilege: Replication slave
  Context: Server Admin
  Comment: To read binary log events from the master
*************************** 25. row ***************************
Privilege: Select
  Context: Tables
  Comment: To retrieve rows from table
*************************** 26. row ***************************
Privilege: Show databases
  Context: Server Admin
  Comment: To see all databases with SHOW DATABASES
*************************** 27. row ***************************
Privilege: Show view
  Context: Tables
  Comment: To see views with SHOW CREATE VIEW
*************************** 28. row ***************************
Privilege: Shutdown
  Context: Server Admin
  Comment: To shut down the server
*************************** 29. row ***************************
Privilege: Super
  Context: Server Admin
  Comment: To use KILL thread, SET GLOBAL, CHANGE MASTER, etc.
*************************** 30. row ***************************
Privilege: Trigger
  Context: Tables
  Comment: To use triggers
*************************** 31. row ***************************
Privilege: Create tablespace
  Context: Server Admin
  Comment: To create/alter/drop tablespaces
*************************** 32. row ***************************
Privilege: Update
  Context: Tables
  Comment: To update existing rows
*************************** 33. row ***************************
Privilege: Usage
  Context: Server Admin
  Comment: No privileges - allow connect only
*************************** 34. row ***************************
Privilege: XA_RECOVER_ADMIN
  Context: Server Admin
  Comment: 
*************************** 35. row ***************************
Privilege: SHOW_ROUTINE
  Context: Server Admin
  Comment: 
*************************** 36. row ***************************
Privilege: SET_USER_ID
  Context: Server Admin
  Comment: 
*************************** 37. row ***************************
Privilege: RESOURCE_GROUP_USER
  Context: Server Admin
  Comment: 
*************************** 38. row ***************************
Privilege: APPLICATION_PASSWORD_ADMIN
  Context: Server Admin
  Comment: 
*************************** 39. row ***************************
Privilege: SYSTEM_VARIABLES_ADMIN
  Context: Server Admin
  Comment: 
*************************** 40. row ***************************
Privilege: AUDIT_ADMIN
  Context: Server Admin
  Comment: 
*************************** 41. row ***************************
Privilege: SERVICE_CONNECTION_ADMIN
  Context: Server Admin
  Comment: 
*************************** 42. row ***************************
Privilege: CLONE_ADMIN
  Context: Server Admin
  Comment: 
*************************** 43. row ***************************
Privilege: PERSIST_RO_VARIABLES_ADMIN
  Context: Server Admin
  Comment: 
*************************** 44. row ***************************
Privilege: FLUSH_USER_RESOURCES
  Context: Server Admin
  Comment: 
*************************** 45. row ***************************
Privilege: BINLOG_ADMIN
  Context: Server Admin
  Comment: 
*************************** 46. row ***************************
Privilege: ROLE_ADMIN
  Context: Server Admin
  Comment: 
*************************** 47. row ***************************
Privilege: SESSION_VARIABLES_ADMIN
  Context: Server Admin
  Comment: 
*************************** 48. row ***************************
Privilege: BINLOG_ENCRYPTION_ADMIN
  Context: Server Admin
  Comment: 
*************************** 49. row ***************************
Privilege: FLUSH_STATUS
  Context: Server Admin
  Comment: 
*************************** 50. row ***************************
Privilege: SYSTEM_USER
  Context: Server Admin
  Comment: 
*************************** 51. row ***************************
Privilege: ENCRYPTION_KEY_ADMIN
  Context: Server Admin
  Comment: 
*************************** 52. row ***************************
Privilege: REPLICATION_SLAVE_ADMIN
  Context: Server Admin
  Comment: 
*************************** 53. row ***************************
Privilege: GROUP_REPLICATION_ADMIN
  Context: Server Admin
  Comment: 
*************************** 54. row ***************************
Privilege: BACKUP_ADMIN
  Context: Server Admin
  Comment: 
*************************** 55. row ***************************
Privilege: RESOURCE_GROUP_ADMIN
  Context: Server Admin
  Comment: 
*************************** 56. row ***************************
Privilege: FLUSH_OPTIMIZER_COSTS
  Context: Server Admin
  Comment: 
*************************** 57. row ***************************
Privilege: TABLE_ENCRYPTION_ADMIN
  Context: Server Admin
  Comment: 
*************************** 58. row ***************************
Privilege: FLUSH_TABLES
  Context: Server Admin
  Comment: 
*************************** 59. row ***************************
Privilege: CONNECTION_ADMIN
  Context: Server Admin
  Comment: 
*************************** 60. row ***************************
Privilege: INNODB_REDO_LOG_ENABLE
  Context: Server Admin
  Comment: 
*************************** 61. row ***************************
Privilege: INNODB_REDO_LOG_ARCHIVE
  Context: Server Admin
  Comment: 
*************************** 62. row ***************************
Privilege: REPLICATION_APPLIER
  Context: Server Admin
  Comment: 
62 rows in set (0.00 sec)

ERROR: 
No query specified

mysql> 

Exercise 1: We now want to grant the manager role read-only access to the commodity information table, inventory table, and accounts payable table, which can be achieved with the following code:

GRANT SELECT ON demo.settlement TO 'manager';
GRANT SELECT ON demo.goodsmaster TO 'manager';
GRANT SELECT ON demo.invcount TO 'manager';

5.4 View role permissions

After granting the role permissions, we can use the SHOW GRANTS statement to check whether the permissions are created successfully:

mysql> SHOW GRANTS FOR 'manager';
+-------------------------------------------------------+
| Grants for manager@% |
+-------------------------------------------------------+
| GRANT USAGE ON *.* TO `manager`@`%` |
| GRANT SELECT ON `demo`.`goodsmaster` TO `manager`@`%` |
| GRANT SELECT ON `demo`.`invcount` TO `manager`@`%` |
| GRANT SELECT ON `demo`.`settlement` TO `manager`@`%` |
+-------------------------------------------------------+

As long as you create a role, the system will automatically give you a "USAGE" permission, which means the permission to connect to the login database. The last three lines of the code represent the permissions we have given to the role "manager", that is, the read-only permissions to the commodity information table, inventory table, and accounts payable table.

The results show that the warehouse management role has the read-only permission of the product information table and the addition, deletion, modification and query permission of the inventory table.

5.5 Reclaim role permissions

After the role is authorized, the permissions of the role can be maintained, and the permissions can be added or revoked. Adding permissions uses the GRANT statement, which is the same as role authorization. To revoke a role or role permissions use the REVOKE statement.

Modifying the permissions of a role will affect the permissions of the account that owns the role.

The SQL syntax for revoking role permissions is as follows:

REVOKE privileges ON tablename FROM 'rolename';

Exercise 1: Revoke the permission of the school_write role. (1) Use the following statement to revoke the permission of the school_write role.

REVOKE INSERT, UPDATE, DELETE ON school.* FROM 'school_write';

(2) After revoking, use the SHOW statement to view the permissions corresponding to school_write, the statement is as follows.

SHOW GRANTS FOR 'school_write';

5.6 Delete role

When we need to reintegrate the business, we may need to clean up the previously created roles and delete some roles that will no longer be used. The operation of deleting a role is very simple, you only need to master the grammatical structure.

DROP ROLE role [,role2]...

Note that if you delete a role, the user loses all privileges gained through the role.

Exercise: Execute the following SQL to delete the role school_read.

DROP ROLE 'school_read';

5.7 Assign roles to users

After a role is created and authorized, it must be assigned to a user and activated to take effect. You can use the GRANT statement to add roles to users, and the syntax is as follows:

GRANT role [,role2,...] TO user [,user2,...];

In the above statement, role represents a role, and user represents a user. Multiple roles can be assigned to multiple users at the same time, separated by commas.

Exercise: Add role school_read permission to kangshifu user. (1) Use the GRANT statement to add school_read permission to kangshifu, the SQL statement is as follows.

GRANT 'school_read' TO 'kangshifu'@'localhost';

(2) After adding, use the SHOW statement to check whether the addition is successful. The SQL statement is as follows.

SHOW GRANTS FOR 'kangshifu'@'localhost';

(3) Log in as the kangshifu user, and then query the current role. If the role is not activated, the result will display NONE. The SQL statement is as follows.

SELECT CURRENT_ROLE();

mysql> SELECT CURRENT_ROLE();
+----------------+
| CURRENT_ROLE() |
+----------------+
| NONE           |
+----------------+
1 row in set (0.00 sec)

mysql> 

5.8 Activate role

Method 1: Use the set default role command to activate the role

Example:

SET DEFAULT ROLE ALL TO 'kangshifu'@'localhost';

Example: Use SET DEFAULT ROLE to activate all existing roles by default for the following 4 users as follows:

SET DEFAULT ROLE ALL TO
'dev1'@'localhost',
'read_user1'@'localhost',
'read_user2'@'localhost',
'rw_user1'@'localhost';

Way 2: Set activate_all_roles_on_login to ON

  • Default:
mysql> show variables like 'activate_all_roles_on_login';
+-----------------------------+-------+
| Variable_name | Value |
+-----------------------------+-------+
| activate_all_roles_on_login | OFF |
+-----------------------------+-------+
1 row in set (0.00 sec)
  • set up:

SET GLOBAL activate_all_roles_on_login=ON;

This SQL statement means to permanently activate all roles. After running this statement, the user actually has all the permissions granted to the role.

5.9 Revoking a User's Role

The SQL syntax for revoking a user role is as follows:

REVOKE role FROM user;

Exercise: Revoke the school_read role from the kangshifu user. (1) The undo SQL statement is as follows

REVOKE 'school_read' FROM 'kangshifu'@'localhost';

(2) After revocation, execute the following query statement to view the role information of the kangshifu user

SHOW GRANTS FOR 'kangshifu'@'localhost';

Execution found that the previous school_read role of user kangshifu has been revoked.

5.10 Set mandatory role (mandatory role)

Method 1: Set before the service starts

[mysqld]
mandatory_roles='role1,role2@localhost,r3@%.atguigu.com'

Method 2: Runtime settings

SET PERSIST mandatory_roles = 'role1,role2@localhost,r3@%.example.com'; #系统重启后仍然
有效
SET GLOBAL mandatory_roles = 'role1,role2@localhost,r3@%.example.com'; #系统重启后失效

Guess you like

Origin blog.csdn.net/fgwynagi/article/details/129962913