跳到主要内容

权限管理

一、权限列表

-- 查看 MySQL 中所有的权限
show privileges;

1、表权限

selectinsertupdatedeletecreatedropgrantreferencesindexalter

2、列权限

selectinsertupdatereferences

3、过程权限

executalert routinegrant

二、权限授予原则

  • 只授予能满足需要的最小权限
  • 创建用户的时候限制用户的登录主机,一般是限制成指定 ip 或者内外 ip 段
  • 为每个用户设置满足密码复杂度的密码
  • 定期清理不需要的用户,回收权限或者删除用户。

三、授予权限

  • 角色赋予用户给用户授权
  • 直接给用户授权

1、语法

grant 权限1,权限2...权限n on 数据库名称.表名称 to 'username'@'host'

2、授权

在授权的时候,最好指明 usernamehost

授予用户 user1 数据库 dbtest1 的增删改查权限

grant select,insert,delete,update on dbtest1.* to user1@localhost;

给 user3 授予所有的权限(grant 权限除外)

grant all privileges on *.* to 'user3'@'localhost';

赋予所有权限,包括 grant 的权限

grant all privileges on *.* to 'user1'@'%' with grant option;

三、查看权限

-- 查看当前用户的权限
show grants;

show grants for current_user;

show grants for current_user();

-- 查看指定用户的权限
show grants for 'username'@'host';

四、权限回收

权限回收的关键字 revoke

收回用户不必要的权限可以在一定程度上保证系统的安全性。

revoke 权限1,...,权限n on database.table from 'username'@'host';

问题1:

mysql> revoke all privileges on *.* from 'user3'@'localhost';     
ERROR 1227 (42000): Access denied; you need (at least one of) the SYSTEM_USER privilege(s) for this operation

解决方案:授予 root 用户 system_user 角色权限

grant system_user on *.* to 'root'@'';

五、刷新权限

flush privileges;

什么时候需要执行 flush privileges

https://cloud.tencent.com/developer/article/1730238