laravel5
MySQL8.0

MySQL8.0 認証方式を変更する

MySQL8.0 を初めてインストールして、
Laravelでマイグレーションを実行したときにエラーがでて罠にハマりました。

環境

$ mysql --version
mysql  Ver 8.0.11 for Linux on x86_64 (MySQL Community Server - GPL)

MySQL8.0.4 デフォルトの認証方式変更

MySQL8.0では、 mysql_native_password ではなく、 caching_sha2_password がデフォルトの認証プラグインとなりました。


6.5.1.3 Caching SHA-2 Pluggable Authentication

Laravel マイグレーションでエラー

$ php artisan migrate
   Illuminate\Database\QueryException  : SQLSTATE[HY000] [2054] The server requested authentication method unknownto the client (SQL: select * from information_schema.tables where table_schema = blog and table_name = migrations)

  at /home/vagrant/blog/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]")
      /home/vagrant/blog/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:68

  2   PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=blog", "vagrant", "P@assw0rd", [])
      /home/vagrant/blog/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:68
  • MySQL8.0.4 以降のログイン認証方式は「caching_sha2_password」でデフォルト
  • PHPのMySQL接続ライブラリが「caching_sha2_password」未対応
  • 認証方式を「mysql_native_password」に戻す

既存ユーザーの認証方式を確認

> SELECT user, host, plugin FROM mysql.user;
+------------------+-----------+-----------------------+
| user             | host      | plugin                |
+------------------+-----------+-----------------------+
| vagrant          | 127.0.0.1 | caching_sha2_password |
| vagrant          | 192.168.% | caching_sha2_password |
| mysql.infoschema | localhost | mysql_native_password |
| mysql.session    | localhost | mysql_native_password |
| mysql.sys        | localhost | mysql_native_password |
| root             | localhost | caching_sha2_password |
| vagrant          | localhost | caching_sha2_password |
+------------------+-----------+-----------------------+

既存ユーザーの認証方式を変更

> ALTER USER 'vagrant'@'127.0.0.1' IDENTIFIED WITH mysql_native_password BY 'P@ssw0rd';
> ALTER USER 'vagrant'@'192.168.%' IDENTIFIED WITH mysql_native_password BY 'P@ssw0rd';
> ALTER USER 'vagrant'@'localhost' IDENTIFIED WITH mysql_native_password BY 'P@ssw0rd';
> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'P@ssw0rd';

新規ユーザー作成時の認証方式を変更

/etc/my.cnf に追記

[mysqld]
default-authentication-plugin = mysql_native_password

最初からこれを設定しておくべきでした。