MySQL 8.0默认认证插件为caching_sha2_password,需在[mysqld]段配置default_authentication_plugin=mysql_native_password并重启服务,且已有用户须单独执行ALTER USER更新plugin字段方可生效。

MySQL 8.0 默认用 caching_sha2_password,老项目连不上基本就是它在拦路;改 default_authentication_plugin 是最直接的解法,但必须配对生效:配置文件改 + 已有用户显式重设。
my.cnf 里加 default_authentication_plugin 为什么有时不生效
常见现象是重启 MySQL 后新创建的用户还是 caching_sha2_password,或者旧用户连接仍报错。原因通常是:
- 没确认 MySQL 实际加载的是哪个
my.cnf—— 它可能从/etc/my.cnf、/etc/mysql/my.cnf、/usr/etc/my.cnf或~/.my.cnf中选一个,优先级高的会覆盖低的 -
default_authentication_plugin只影响「新创建的用户」,对已存在的用户(比如升级前就有的root)完全没作用 - 该配置项必须放在
[mysqld]段下,写在[client]或[mysql]里无效 - 修改后没重启 MySQL 服务,或用了
systemctl reload mysqld(这不会重读认证插件配置,必须restart)
怎么查 MySQL 当前加载了哪个 my.cnf
运行这条命令就能看到真实路径和加载顺序:
mysqld --help --verbose | grep "Default options"
输出类似:
Default options are read from the following files in the given order: /etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf
你只需要往第一个存在的文件(通常是 /etc/my.cnf)的 [mysqld] 段末尾加一行:
[mysqld] default_authentication_plugin=mysql_native_password
加完保存,然后执行:
sudo systemctl restart mysqld
为什么改了 default_authentication_plugin 还连不上 root
因为 root 用户是在 MySQL 8.0 升级前就存在的,它的 plugin 字段仍为 caching_sha2_password,不受全局配置影响。必须手动更新:
- 先用临时方式登录(比如跳过权限检查,或用 socket 登录)
- 执行:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '你的密码'; - 如果要支持远程 root 登录,还得补一句:
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '你的密码'; - 最后别忘:
FLUSH PRIVILEGES;
验证是否成功:SELECT user, host, plugin FROM mysql.user WHERE user = 'root'; —— 输出的 plugin 列必须是 mysql_native_password。
客户端连不上时,先看错误信息再动手
典型报错包括:
-
Client does not support authentication protocol requested by server→ 确认客户端 libmysqlclient 版本太低,或服务端用户没切认证插件 -
Access denied for user 'xxx'@'xxx'→ 先查mysql.user表确认该用户的plugin和密码是否匹配,不是单纯改配置就能解决 - PHP 的
mysqli或PDO_MySQL报错 → 它们至今不支持caching_sha2_password,必须把对应用户改成mysql_native_password
真正麻烦的从来不是改哪行配置,而是得同时处理「新用户默认行为」和「老用户当前状态」两件事 —— 少做一步,连接就卡住。


















