新项目采用MySQL8.0开发,对接数据库时出现以下异常
[root@xxx dir]# php artisan migrate
Illuminate\Database\QueryException : SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client (SQL: select * from information_schema.tables where table_schema = dbname and table_name = migrations)
at /var/www/dir/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 PDOException::("PDO::__construct(): The server requested authentication method unknown to the client [caching_sha2_password]")
/var/www/dir/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
2 PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=dbname", "root", "password", [])
/var/www/dir/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
Please use the argument -v to see more details.
实际上根据不同的PHP MySQL扩展 可能出现两种实际的异常:
Warning: mysqli_connect(): The server requested authentication
method unknown to the client [caching_sha2_password]
Warning: PDO::__construct(): The server requested authentication method unknown to the client [caching_sha2_password]
研究后发现,这是因为MySQL8采用了新的密码验证方法 我们阅读MySQL8 change log看到了Oracle官方的解决方案:
Important If your MySQL installation must serve pre-8.0 clients and you encounter compatibility issues after upgrading to MySQL 8.0 or higher, the simplest way to address those issues and restore pre-8.0 compatibility is to reconfigure the server to revert to the previous default authentication plugin (mysql_native_password). For example, use these lines in the server option file:
[mysqld]
default_authentication_plugin=mysql_native_password
That setting enables pre-8.0 clients to connect to 8.0 servers until such time as the clients and connectors in use at your installation are upgraded to know about caching_sha2_password. However, the setting should be viewed as temporary, not as a long term or permanent solution, because it causes new accounts created with the setting in effect to forego the improved authentication security provided by caching_sha2_password.
大意为:如果客户端不支持新的验证方式,临时解决方案是在my.cnf中加入 default_authentication_plugin=mysql_native_password
, 不过这个操作是临时的,请尽快解决这个问题,因为新的验证方式可以提供更好的安全性。
我们在/etc/my.cnf中加入
default_authentication_plugin=mysql_native_password
保存后 重启mysqld
service mysqld restart
再次重试依然报同样错误。
参考 https://www.cnblogs.com/yhqvod/p/8930980.html 的解决方案,创建新的MySQL用户
CREATE USER 'developer'@'localhost' IDENTIFIED BY 'password';
GRANT privileges ON databasename.tablename TO 'developer'@'localhost';
修改项目相应数据库配置信息,执行成功。