search
HomeDatabaseMysql TutorialMySQL permissions and security management

Mysql permission system is very important, but at the same time it is something that many developers or managers ignore. Not only the distribution of authority will lead to irreparable tragic consequences. The company I worked for before didn't pay much attention to database permissions at all. All developers had the highest permissions for the online system. Think about it, if one of them deletes the database one day, do you know who did it among so many people? Therefore, everyone must pay attention to it.

It is generally recommended that the highest authority is given to only one person, and this person serves as the manager and then allocates corresponding permissions to other developers. Local libraries are better during the development stage. For online libraries, be careful when granting permissions.

The principle of authority authentication

MySQL's authority authentication is authenticated through two aspects. First, the user's IP, user name and password will be verified. Only users who pass the verification can connect to Mysql. When connected, when the user performs any operation, Mysql will verify the permissions it has. Only with the permissions, the operation requested by the user will be performed. Otherwise, it is not executed.

Mysql permission classification

MySQL permissions are roughly divided into three categories:

  • Data operations, such as adding, deleting, modifying, and checking.

  • Structural operations, such as creating libraries, modifying table structures, etc.

  • Management permissions, such as creating users, assigning permissions, etc.

Mysql permission allocation principle

  • Give the minimum permissions, for example, the user currently only needs If you have read permissions and only need to see one table, then don't assign read permissions to all tables. Limit permissions to only one table. Don't be afraid of the trouble of giving read permissions to all tables.

  • When creating a user, be sure to restrict IP addresses and set a password with sufficient strength.

  • Regularly clean up unnecessary users and reclaim unnecessary permissions.

Account management

Create account

The syntax for creating a user in the mysql document is as follows:

CREATE USER [IF NOT EXISTS]
    user [auth_option] [, user [auth_option]] ...
    [REQUIRE {NONE | tls_option [[AND] tls_option] ...}]
    [WITH resource_option [resource_option] ...]
    [password_option | lock_option] ...

There are a lot of parameters, don’t worry, take your time and look at the examples. Start by creating an account with minimal options.

# 创建一个无需密码即可本地登录的用户
mysql> CREATE USER 'u1'@'localhost';
Query OK, 0 rows affected

# 创建一个需要密码授权的用户,但不限制ip
mysql> CREATE USER 'u2'@'%' identified by '321232';
# 注意,密码必须使用引号,单引号或双引号都行,但不加就出错。

# 如果不想使用明文的密码,可以使用password
mysql> select password('111111');
+-------------------------------------------+
| password('111111')                        |
+-------------------------------------------+
| *FD571203974BA9AFE270FE62151AE967ECA5E0AA |
+-------------------------------------------+
1 row in set
mysql> CREATE USER 'u3'@'192.168.1.%' IDENTIFIED BY PASSWORD '*FD571203974BA9AFE270FE62151AE967ECA5E0AA';
Query OK, 0 rows affected

View user list

The system user list is stored in the user table in the mysql library.

mysql> SELECT user,host,account_locked FROM mysql.user;
--------------- ------------- ----------------
| user | host | account_locked |
--------------- ------ ------- -------------
| root | localhost | N |
| mysql.session | localhost | Y |
| mysql .sys | localhost | Y |
| u1 | localhost | N |
| u2 | % | N | localhost | N |
| u3 | 192.168.1.% | N |
------------------ ---------------- ----------------
7 rows in set

Delete user

The syntax for deleting a user is as follows:

DROP USER 用户名@ip;

Now let’s delete u2@ '%'

mysql> drop user u2@'%';
Query OK, 0 rows affected

The u2 user will be deleted.

Modify user account

The syntax is as follows:

rename user old@'oldip' to new@'newip';

The case is as follows:

mysql> RENAME USER u1@localhost to user1@'127.0.0.1';
Query OK, 0 rows affected

Authorization

学完了如何创建账号及管理账号后,我们来看看如何给用户授权以及如何回收不需要的权限。

用户授权

给用户授权语法如下:

GRANT 权限 ON 数据库名*表名 TO 用户名@ip;

案例如下:

mysql> GRANT SELECT ON *.* TO 'u1'@'localhost' ; 
Query OK, 0 rows affected (0.00 sec) 
-- 全局级别授权   
mysql> GRANT ALL ON test.* TO 'u2'@'localhost'; 
Query OK, 0 rows affected (0.00 sec) 
-- 数据库级别授权   
mysql> GRANT ALL ON test.student TO 'u3'@'localhost' WITH GRANT OPTION; 
-- 表级别授权

查看用户的权限

给用户授权后,我们来查看用户是否已经获得到了这些权限。

回收用户权限

当发现给与的权限多了,那么就应该及时回收这些权限。回收权限的语法和授权的语法非常像。

REVOKE 权限 ON 数据库*表 FROM 用户名@ip地址

The above is the detailed content of MySQL permissions and security management. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor