【MySQL】認証方式を変更

もじく

環境

事象

Laravelでマイグレートしようとしたら、エラーが出ました。確認すると、認証方式が間違っているようなので変更します。

初期値のままだとこういうエラーが起きるようです。

また、例えばDockerの内部でMySQLを起動している場合Docker再起動などでも初期値に戻ってしまうぽいです。その場合は再度変更が必要です。

エラー内容

$ php artisan migrate

   Illuminate\Database\QueryException 

  SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client

手順

データベースを指定して現状を確認

MySQLへログインして行ってください。

現在の認証方式を確認します。

認証方式を確認する前にまずどのデータベースかを選択する必要があります。

ここで私は勘違いしてドツボにはまったんですが選択するデータベースはmysqlです。自分が作成したデータベースではなく初めからあるmysqlを選択してください。

mysql > use mysql;
mysql > select user, host, plugin from user;
+------------------+-----------+-----------------------+
| user             | host      | plugin                |
+------------------+-----------+-----------------------+
| xxxx             | 127.0.0.1 | caching_sha2_password |
| yyyy             | localhost | caching_sha2_password |
| mysql.infoschema | localhost | caching_sha2_password |
| mysql.session    | localhost | caching_sha2_password |
| mysql.sys        | localhost | caching_sha2_password |
| root             | localhost | caching_sha2_password |
+------------------+-----------+-----------------------+

認証方法を変更

変更したい分だけ実行しましょう。

今回はxxxxyyyyを変更します。

mysql> alter user 'xxxx'@'127.0.0.1' identified with mysql_native_password by 'ここにパスワード';
mysql> alter user 'yyyy'@'localhost' identified with mysql_native_password by 'ここにパスワード';

確認

mysql> select user, host, plugin from user;
+------------------+-----------+-----------------------+
| user             | host      | plugin                |
+------------------+-----------+-----------------------+
| xxxx             | 127.0.0.1 | mysql_native_password |
| yyyy             | localhost | mysql_native_password |
| mysql.infoschema | localhost | caching_sha2_password |
| mysql.session    | localhost | caching_sha2_password |
| mysql.sys        | localhost | caching_sha2_password |
| root             | localhost | caching_sha2_password |
+------------------+-----------+-----------------------+

かんせい。

マイグレートも難なく完了できました。

参考URL

【MySQL】PHPで接続できないとき SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client | 困った時に思い出したい