当前位置:网站首页>Mysql21 user and permission management
Mysql21 user and permission management
2022-07-06 10:37:00 【Protect our party a Yao】
One . User management
1.1. Sign in MySQL The server
start-up MySQL After service , Can pass mysql Command to log in MySQL The server , The order is as follows :
mysql –h hostname|hostIP –P port –u username –p DatabaseName –e "SQL sentence "
The parameters in the command are described in detail below :
- -h Parameters Followed by host name or host IP,hostname For the host ,hostIP For the host IP.
- -P Parameters Followed by MySQL Port of service , Connect to the specified port through this parameter .MySQL The default port of the service is 3306, Automatically connect to... When this parameter is not used 3306 port ,port Is the port number of the connection .
- -u Parameters Followed by the user name ,username Username .
- -p Parameters Will prompt for password .
- DatabaseName Parameters Indicate which database to log into . If there is no such parameter , Will log in directly to MySQL In the database , And then you can use USE Command to select the database .
- -e Parameters You can directly add SQL sentence . Sign in MySQL The server can then execute this SQL sentence , And then quit MySQL The server .
mysql -uroot -p -hlocalhost -P3306 mysql -e 'select user,host from user'
1.2. Create user
CREATE USER The basic syntax of a sentence is as follows :
CREATE USER user name [IDENTIFIED BY ' password '][, user name [IDENTIFIED BY ' password ']];
- The user name parameter indicates the account of the new user , from user (User) and Host name (Host) constitute ;
- “[ ]” Said the optional , in other words , You can specify that users need password authentication when logging in , You can also not specify password authentication , In this way, users can log in directly . however , It's not safe not to specify a password , It is not recommended to use . If you specify a password value , You need to use IDENTIFIED BY Specify the plaintext password value .
- CREATE USER Statement can create multiple users at the same time .
create user 'zhang3' identified by '123456';# Default host yes %
create user 'kangshifu'@'localhost' identified by '123456';
1.3. Modify the user
Change user name :
update mysql.user set user=li4 where user='kangshifu';
flush privileges;
1.4. Delete user
The way 1: Use DROP Way to delete ( recommend )
Use DROP USER Statement to delete a user , Must be used for DROP USER jurisdiction .DROP USER The basic syntax of a sentence is as follows :
DROP USER user[,user]...;
give an example :
DROP USER li4 ; # Delete by default host by % Users of
DROP USER 'kangshifu'@'localhost';
The way 2: Use DELETE Way to delete
DELETE FROM mysql.user WHERE Host=’hostname’ AND User=’username’;
After execution DELETE After the command, use FLUSH Command to make the user effective , The order is as follows :
FLUSH PRIVILEGES;
Be careful : It is not recommended to pass DELETE FROM USER u WHERE USER=‘li4’ To delete , There will be residual information in the system . and drop user The command will delete the user and the corresponding permissions , After executing the command, you will find mysql.user Table and mysql.db The corresponding records of the table disappeared .
1.5. Set current user password
The old wording is as follows :
# Change the password of the current user :(MySQL5.7 The test works )
SET PASSWORD = PASSWORD('123456');
Here are Recommended writing :
- Use ALTER USER Command to change the current user password Users can use ALTER Command to change your password , The following statement represents modifying the password of the current login user . The basic grammar is as follows :
ALTER USER USER() IDENTIFIED BY 'new_password';
- Use SET Statement to modify the current user password Use root The user login MySQL after , have access to SET Statement to change the password , Specifically SQL The statement is as follows :
SET PASSWORD='new_password';
This statement will automatically encrypt the password and then assign it to the current user .
1.6. Change other user passwords
- Use ALTER Statement to change the password of ordinary users have access to ALTER USER Statement to change the password of ordinary users . The basic grammatical form is as follows :
ALTER USER user [IDENTIFIED BY ' New password ']
[,user[IDENTIFIED BY ' New password ']]...;
- Use SET Command to change the password of ordinary users Use root The user logs in to MySQL After the server , have access to SET Statement to change the password of ordinary users .SET The code of the statement is as follows :
SET PASSWORD FOR 'username'@'hostname'='new_password';
- Use UPDATE Statement to change the password of an ordinary user ( Not recommended )
UPDATE MySQL.user SET authentication_string=PASSWORD("123456")
WHERE User = "username" AND Host = "hostname";
1.7. MySQL8 Password management ( understand )
1.7.1. Password expiration policy
- stay MySQL in , Database administrators can Manual settings Account password expired , You can build one Automatically Password expiration policy .
- The expiration policy can be Overall , It can also be for Every account Set a separate expiration policy .
ALTER USER user PASSWORD EXPIRE;
alter user 'zhang3' password expire;
- The way ①: Use SQL Statement to change the value of the variable and persist it
set persist default_password_lifetime =360; # Establish a global policy , Set password every 180 Days overdue
- The way ②: The configuration file my.cnf Maintenance in
mysqld]
default_password_lifetime=180 # Establish a global policy , Set password every 180 Days overdue
- Manually set the specified time expiration method 2: Set separately
Each account can use the global password expiration policy , You can also set the policy separately . stay CREATE USER and ALTER USER Add... To the statement PASSWORD EXPIRE Option to set the policy separately . Here are some examples of statements .
# Set up kangshifu Account and password every 90 Days overdue :
CREATE USER 'kangshifu'@'localhost' PASSWORD EXPIRE INTERVAL 90 DAY;
ALTER USER 'kangshifu'@'localhost' PASSWORD EXPIRE INTERVAL 90 DAY;
# Set password never expires :
CREATE USER 'kangshifu'@'localhost' PASSWORD EXPIRE NEVER;
ALTER USER 'kangshifu'@'localhost' PASSWORD EXPIRE NEVER;
# Extend the global password expiration policy :
CREATE USER 'kangshifu'@'localhost' PASSWORD EXPIRE DEFAULT;
ALTER USER 'kangshifu'@'localhost' PASSWORD EXPIRE DEFAULT
1.7.2. Password reuse policy
- Reuse password manually 1: overall situation
The way ①: Use SQL
SET PERSIST password_history = 6; # Recent settings cannot be used 6 A code
SET PERSIST password_reuse_interval = 365; # You cannot select the password in the last year
The way ②:my.cnf The configuration file
[mysqld]
password_history=6
password_reuse_interval=365
- Reuse password manually 2: Set separately
# You cannot use the latest 5 A code :
CREATE USER 'kangshifu'@'localhost' PASSWORD HISTORY 5;
ALTER USER 'kangshifu'@'localhost' PASSWORD HISTORY 5;
# You cannot use the latest 365 Password within days :
CREATE USER 'kangshifu'@'localhost' PASSWORD REUSE INTERVAL 365 DAY;
ALTER USER 'kangshifu'@'localhost' PASSWORD REUSE INTERVAL 365 DAY;
# You can't use the latest 5 A code , Can't be used 365 Password within days
CREATE USER 'kangshifu'@'localhost'
PASSWORD HISTORY 5
PASSWORD REUSE INTERVAL 365 DAY;
ALTER USER 'kangshifu'@'localhost'
PASSWORD HISTORY 5
PASSWORD REUSE INTERVAL 365 DAY;
Two . Rights management
2.1. Permission list
MySQL What kind of authority do you have ?
show privileges;
- CREATE and DROP jurisdiction , You can create new databases and tables , Or delete ( move away ) Existing databases and tables . If you will MySQL In the database DROP Permission granted to a user , The user can delete MySQL Access rights to the saved database .
- SELECT、INSERT、UPDATE and DELETE jurisdiction Allow operations on existing tables in a database .
- SELECT Permissions are only used when they actually retrieve rows from a table .
- INDEX jurisdiction Allow indexes to be created or deleted ,INDEX Applicable to existing tables . If you have a table CREATE jurisdiction , You can go to CREATE TABLE Include the index definition in the statement .
- ALTER jurisdiction have access to ALTER TABLE To change the table structure and rename the table .
- CREATE ROUTINE jurisdiction To create a saved program ( Functions and programs ),ALTER ROUTINE Permissions are used to change and delete saved programs , EXECUTE jurisdiction Used to execute saved programs .
- GRANT jurisdiction Allow authorization to other users , It can be used in database 、 Tables and stored programs .
- FILE jurisdiction So that users can use LOAD DATA INFILE and SELECT … INTO OUTFILE Statement to read or write to a file on the server , Any person who is granted FILE Users with permissions can read or write MySQL Any file on the server ( The user can read any file in the database directory , Because the server can access these files ).
2.2. The principle of granting authority
Access control is mainly for security reasons , Therefore, we need to follow the following Experience principle :
- Only... Can be granted The minimum permissions required , Prevent users from doing bad things . For example, users just need to query , Then just select Authority is enough , Don't give users update、insert perhaps delete jurisdiction .
- When creating users Restrict the user's Login Host , Generally, it is limited to designated IP Or the Internet IP paragraph .
- For each user Set a password that meets the password complexity .
- Clean up unwanted users regularly , Reclaim permissions or delete users .
2.3. Grant authority
There are ways to authorize users 2 Kind of , By putting The role gives the user authorization and Authorize users directly . The user is the user of the database , We can grant users access to resources in the database by , To control users' access to the database , Eliminate safety hazards .
Authorization command :
GRANT jurisdiction 1, jurisdiction 2,... jurisdiction n ON Database name . The name of the table TO user name @ Address of the user [IDENTIFIED BY ‘ Password ’];
If it is found that the user does not have this permission , A new user will be created directly .
such as :
to zhang3 The user uses the local command line mode , grant MYSQLTEST The permission of inserting, deleting, modifying and querying all tables in this library .
GRANT SELECT,INSERT,DELETE,UPDATE ON MYSQLTEST.* TO zhang3;
Granted to log in through the network joe user , Full permissions for all libraries, all tables , The password is set to 123. Note that only... Is not included here grant Authority
GRANT ALL PRIVILEGES ON *.* TO [email protected]'%' IDENTIFIED BY '123456';
When we are developing applications , There is often a need , According to different users , Group data horizontally and vertically .
- The so-called horizontal grouping , It refers to the range of data that users can access , For example, you can see the data of which tables ;
- The so-called vertical grouping , It refers to the extent to which users can access the data they are exposed to , For example, you can see 、 Can change , Even delete .
2.4. View permissions
- View current user permissions
SHOW GRANTS;
# or
SHOW GRANTS FOR CURRENT_USER;
# or
SHOW GRANTS FOR CURRENT_USER();
- View a user's global permissions
SHOW GRANTS FOR 'user'@' The host address ' ;
2.5. Take back authority
Withdrawing permissions means canceling some permissions that have been given to users . Taking back users' unnecessary permissions can ensure the security of the system to a certain extent .MySQL Use in REVOKE sentence Cancel some permissions of the user . Use REVOKE After taking back the authority , The record of user account will be from db、host、tables_priv and columns_priv In the table to delete , But user account records are still user Save in the table ( Delete user The account records in the table use DROP USER sentence ).
Be careful : The user account is being removed from user Before deleting the table , All permissions of the corresponding user should be revoked .
- Withdraw permission command :
REVOKE jurisdiction 1, jurisdiction 2,... jurisdiction n ON Database name . The name of the table FROM user name @ Address of the user ;
- give an example
# Take back all permissions of the whole database and table
REVOKE ALL PRIVILEGES ON *.* FROM [email protected]'%';
# Take back mysql Insert, delete, modify and query permissions for all tables under the database
REVOKE SELECT,INSERT,UPDATE,DELETE ON mysql.* FROM [email protected];
Be careful : It can only take effect after the user logs in again
3、 ... and . Permissions on the table
3.1. user surface
user Table is MySQL The most important permission table in , Record user account and permission information , Yes 49 A field . Here's the picture :
These fields can be divided into 4 class , They are the range Columns ( Or user Columns )、 Permission list 、 Security column and resource control column .
3.1. 1. Range column ( Or user Columns )
- host : Indicates the connection type
- % Indicates that all remote passes TCP Way of connection .
- IP Address Such as (192.168.1.2、127.0.0.1) By making ip Address TCP Way of connection .
- machine name By specifying the name of the machine in the network TCP Way of connection .
- ::1 IPv6 The local ip Address , Equate to IPv4 Of 127.0.0.1
- localhost Local mode connection through command line mode , such as mysql -u xxx -p xxx Way of connection .
- user : Represents the user name , The permissions of the same user are different through different links .
- password : password
- All password strings pass through password( Plaintext string ) Generated ciphertext string .MySQL 8.0 Added role management in user management , The default password encryption method has also been adjusted , By the previous SHA1 Change it to SHA2 , Irreversible . At the same time plus MySQL 5.7 Disable users and user expiration features ,MySQL The function and security of user management are greatly enhanced compared with the previous version .
- mysql 5.7 And later versions of passwords are saved to authentication_string Field is no longer used password Field .
3.1.2. Permission list
- Grant_priv Field : Indicates whether you have GRANT jurisdiction .
- Shutdown_priv Field : Indicates whether you have a stop MySQL Authority of service .
- Super_priv Field : Indicates whether you have super permissions .
- Execute_priv Field : Indicates whether you have EXECUTE jurisdiction . Have EXECUTE jurisdiction , Can execute stored procedures and functions .
- Select_priv , Insert_priv etc. : For the permissions that the user has .
3.1.3. Security column
The only safe train is 6 A field , Two of them are ssl dependent (ssl_type、ssl_cipher), be used for encryption ; Two are x509 dependent (x509_issuer、x509_subject), be used for Identify users ; The other two Plugin Fields are used for Verify user identity Plug in for , This field cannot be empty . If the field is empty , The server uses the built-in authorization authentication mechanism to verify the user's identity .
3.1.4. Resource control column
The fields in the resource control column are used to Restrict resources used by users , contain 4 A field , Respectively :
①max_questions, The number of query operations allowed by the user per hour ;
②max_updates, The number of update operations allowed by the user per hour ;
③max_connections, The number of connection operations allowed by the user per hour ;
④max_user_connections, Number of simultaneous connections allowed by the user .
View fields :
DESC mysql.user;
To view the user , Display data in columns :
SELECT * FROM mysql.user \G;
Query specific fields :
SELECT host,user,authentication_string,select_priv,insert_priv,drop_priv
FROM mysql.user;
3.2. db surface
Use DESCRIBE see db The basic structure of the table :
DESCRIBE mysql.db;
- User column db The user table lists 3 A field , Namely Host、User、Db. this 3 Each field represents the host name 、 User name and database name . Indicates the operation permission of a user connected from a host to a database , this 3 The combination of two fields constitutes db Primary Key .
- Permission list Create_routine_priv and Alter_routine_priv These two fields determine whether the user has permission to create and modify stored procedures .
3.3. tables_priv Table and columns_priv surface
tables_priv Table used Set operation permissions on the table ,columns_priv A table is used to compare the Set permissions for a column .tables_priv Table and columns_priv The structure of the table is shown in Fig :
desc mysql.tables_priv;
tables_priv Table has 8 A field , Namely Host、Db、User、Table_name、Grantor、Timestamp、Table_priv and Column_priv, Each field is described below :
- Host 、 Db 、 User and Table_name The four fields represent the host name 、 Database name 、 User name and table name .
- Grantor Indicates the user who modified the record .
- Timestamp Indicates the time when the record was modified .
- Table_priv Indicates the operation permission of the object . Include Select、Insert、Update、Delete、Create、Drop、Grant、References、Index and Alter.
- Column_priv Field indicates the operation permission of the column in the table , Include Select、Insert、Update and References.
desc mysql.columns_priv;
3.4. procs_priv surface
procs_priv A watch can be used to Set operation permissions for stored procedures and stored functions , The table structure is shown in the figure :
desc mysql.procs_priv;
Four . Access control ( understand )
4.1. Connection verification phase
When a user tries to connect MySQL Server time , The server determines whether to accept or reject the connection based on the user's identity and whether the user can provide the correct password authentication identity . That is, the client user will provide the user name in the connection request 、 The host address 、 User password ,MySQL After the server receives the user request , Will use user In the table host、user and authentication_string this 3 Fields match the information provided by the client .
The server is only in user It's recorded in the table Host and User Field matches the client hostname and user name , And only accept the connection when you provide the correct password . If the connection verification fails , The server completely denies access ; otherwise , Server accepts connection , Then we go to the stage 2 Waiting for user requests .
4.2. Request verification phase
Once the connection is established , The server enters the stage of access control 2, That is, the request verification phase . Every request that comes in on this connection , The server checks what to do with the request 、 Whether there are enough permissions to execute it , This is where the permission column in the authorization table is needed to play a role . These permissions can come from user、db、table_priv and column_priv surface .
When confirming permissions ,MySQL First Check user surface , If the specified permission is not in user Granted... In the table , that MySQL Will continue Check db surface ,db Table is the next level of security , The permissions are limited to the database level , At this level SELECT Permissions allow users to view data in all tables in a specified database ; If no qualified permission is found at this level , be MySQL continue Check tables_priv surface as well as columns_priv surface , If all permission tables are checked , But no permission operation was found ,MySQL take Return error message , The operation requested by the user cannot be performed , operation failed .
Tips : MySQL Through the order of down levels ( from user Table to columns_priv surface ) Check the permission table ,
But not all permissions need to execute this process . for example , A user logs in to MySQL Server
Only execute pair after MySQL Management operation of , At this time, only administrative permissions are involved , therefore MySQL Check only user surface .
in addition , If the requested permission operation is not allowed ,MySQL It will not continue to check the table at the next level .
5、 ... and . Role management
5.1. The understanding of the role
The purpose of introducing roles is It is convenient to manage users with the same permissions . Appropriate permission settings , It can ensure the security of data , This is crucial .
5.2. Create the role
Create characters to use CREATE ROLE sentence , The grammar is as follows :
CREATE ROLE 'role_name'[@'host_name'] [,'role_name'[@'host_name']]...
The naming rules of role names are similar to user names . If host_name Omit , The default is % , role_name Do not omit , Do not empty .
practice : We now need to create a manager role , You can use the following code :
create role 'manager'@'localhost';
5.3. Give the role permission
After creating the role , By default, this role does not have any permissions , We need to authorize the role . The syntax structure for authorizing roles is :
GRANT privileges ON table_name TO 'role_name'[@'host_nam
In the above sentence privileges The name representing the permission , Multiple permissions are separated by commas . You can use SHOW Statement query permission name , chart 11-43 Lists some permissions .
SHOW PRIVILEGES\G;
5.4. View role permissions
After giving the role permission , We can go through SHOW GRANTS sentence , To see if the permission has been created successfully :
As long as you create a character , The system will automatically give you a “ USAGE ” jurisdiction , intend Permission to connect and log in to the database .
GRANT all PRIVILEGES ON *.* TO 'manager'@'localhost';
5.5. Reclaim role permissions
After role authorization , You can maintain the permissions of roles , Add or revoke permissions . Add permission to use GRANT sentence , Same as role authorization . Revoke role or role permission use REVOKE sentence .
Modified the permission of the role , It will affect the permission of the account with this role .
Revoke role permissions SQL The grammar is as follows :
REVOKE privileges ON tablename FROM 'rolename';
5.6. Delete the role
When we need to re integrate our business , You may need to clean up the previously created roles , Delete some roles that will no longer be used . The operation of deleting roles is very simple , You just need to master the grammatical structure .
DROP ROLE role [,role2]...
Be careful , If you delete a character , Then the user will lose all the permissions obtained through this role .
5.7. Give users roles
After the role is created and authorized , To be assigned to the user and in active To make a difference . Adding roles to users can use GRANT sentence , The grammatical form is as follows :
GRANT role [,role2,...] TO user [,user2,...];
In the above statement ,role Representative role ,user On behalf of the user . Multiple roles can be assigned to multiple users at the same time , Separate them with commas .
practice : to kangshifu Users add roles school_read jurisdiction .
(1) Use GRANT Sentence to kangshifu add to school_read jurisdiction ,SQL The statement is as follows .
GRANT 'school_read' TO 'kangshifu'@'localhost';
(2) Use... After adding SHOW Statement to see if the addition is successful ,SQL The statement is as follows .
SHOW GRANTS FOR 'kangshifu'@'localhost';
(3) Use kangshifu The user login , Then query the current role , If the role is not activated , The results will show NONE.SQL The statement is as follows .
SELECT CURRENT_ROLE();
5.8. Activate role
The way 1: Use set default role The command activates the character
give an example :
SET DEFAULT ROLE ALL TO 'kangshifu'@'localhost';
give an example : Use SET DEFAULT ROLE For the following 4 Users activate all existing roles by default as follows :
SET DEFAULT ROLE ALL TO
'dev1'@'localhost',
'read_user1'@'localhost',
'read_user2'@'localhost',
'rw_user1'@'localhost';
The way 2: take activate_all_roles_on_login Set to ON
- By default :
Set up :
SET GLOBAL activate_all_roles_on_login=ON;
This article SQL The meaning of the sentence is , Yes All characters are permanently activated . After running this statement , The user really has all the permissions assigned to the role .
5.9. Remove the user's role
Undo the user role SQL The grammar is as follows :
REVOKE role FROM user;
5.10. Set mandatory roles (mandatory role)
The way 1: Set before service startup
[mysqld]
mandatory_roles='role1,[email protected],[email protected]%.zyy.com'
The way 2: Runtime settings
SET PERSIST mandatory_roles = 'role1,[email protected],[email protected]%.example.com'; # After the system restarts, it still
It works
SET GLOBAL mandatory_roles = 'role1,[email protected],[email protected]%.example.com'; # Failure after system restart
边栏推荐
- February 13, 2022-3-middle order traversal of binary tree
- MySQL35-主从复制
- MySQL22-逻辑架构
- A necessary soft skill for Software Test Engineers: structured thinking
- Implement context manager through with
- 第一篇博客
- 解决在window中远程连接Linux下的MySQL
- Global and Chinese markets for aprotic solvents 2022-2028: Research Report on technology, participants, trends, market size and share
- [paper reading notes] - cryptographic analysis of short RSA secret exponents
- [Julia] exit notes - Serial
猜你喜欢
Pytoch LSTM implementation process (visual version)
MySQL22-逻辑架构
MySQL26-性能分析工具的使用
MySQL实战优化高手11 从数据的增删改开始讲起,回顾一下Buffer Pool在数据库里的地位
Database middleware_ MYCAT summary
MySQL底层的逻辑架构
保姆级手把手教你用C语言写三子棋
How to change php INI file supports PDO abstraction layer
Super detailed steps for pushing wechat official account H5 messages
Mysql34 other database logs
随机推荐
【C语言】深度剖析数据存储的底层原理
MySQL storage engine
Database middleware_ MYCAT summary
Mysql36 database backup and recovery
API learning of OpenGL (2004) gl_ TEXTURE_ MIN_ FILTER GL_ TEXTURE_ MAG_ FILTER
How to find the number of daffodils with simple and rough methods in C language
February 13, 2022 - Maximum subarray and
[after reading the series of must know] one of how to realize app automation without programming (preparation)
如何搭建接口自动化测试框架?
使用OVF Tool工具从Esxi 6.7中导出虚拟机
MNIST implementation using pytoch in jupyter notebook
软件测试工程师发展规划路线
MySQL实战优化高手07 生产经验:如何对生产环境中的数据库进行360度无死角压测?
MySQL21-用户与权限管理
Global and Chinese market of thermal mixers 2022-2028: Research Report on technology, participants, trends, market size and share
MySQL24-索引的数据结构
MySQL25-索引的创建与设计原则
Windchill配置远程Oracle数据库连接
Pytoch LSTM implementation process (visual version)
Moteur de stockage mysql23