Mysql ошибка 2054

Получать MySQL error под Новый Год это уже стало доброй традицией для меня 🙂 . Буквально чуть больше года назад я получал ошибки связанные с БД и теперь снова получаю их обновившись до 8 версии…

Обновил свой MySQL до 8 версии и стал получать error connect ошибку при подключении к БД. А все потому что в 8 версии по умолчанию используется auth_socket соединения. В итоге, мои сайты, которые использовали пароли в конфигурации подключения к БД стали генерировать ошибку:

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

MySQL error — как исправить ошибку?

Поэтому я активно начал искать выход из сложившейся ситуации. Быстрое гугление не дало никаких положительных результатов, пока не наткнулся на подходящую проблему на stackoverflow. Решение заключалось в изменении стандартного метода авторизации на mysql_native_password.

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password
BY 'password';  

В коде выше замените ‘password’ на свой пароль или оставьте поле пустым в кавычках ». После этого ошибка должна исчезнуть и можно дальше работать  😎 .

Полностью ошибка звучит так

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

Причины возникновения — связка MySQL 8 и PHP 7.  Дословно — при подключении к бд не воспринимается метод аутентификации. Причина в том, что в MySQL 8 используется методика аутентификации, отличная от предыдущих версий. В MySQL 8 была изменена схема хранения пароля, начиная с версии 8.0.4 длина хэша пароля увеличена до максимального (255 символов), а также изменили плагин аутентификации – вместо mysql_native_password используется caching_sha2_password. Потому, авторизоваться паролем, который был создан для подключения например пользователем bazauser при установке базы данных, не получиться.

Чтобы авторизация прошла достаточно выполнить следующую команду в консоли MySQL 

ALTER USER ‘bazauser’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘newpassword’;

где bazauser — ваше имя пользователя, newpassword — ваш пароль пользователя

I’m running MySQL version 8 on PHP 7.0.

I’m getting the following error when I try to connect to my database from PHP:

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

PHP might show this error

Warning: mysqli_connect(): The server requested authentication method unknown to the client [caching_sha2_password] in D:xampphtdocsregserver.php on line 10

How can I fix this problem?

Machavity's user avatar

Machavity

30.7k27 gold badges91 silver badges100 bronze badges

asked Sep 17, 2018 at 9:17

mohammed yaser's user avatar

mohammed yasermohammed yaser

2,2512 gold badges11 silver badges16 bronze badges

2

@mohammed, this is usually attributed to the authentication plugin that your mysql database is using.

By default and for some reason, mysql 8 default plugin is auth_socket. Applications will most times expect to log in to your database using a password.

If you have not yet already changed your mysql default authentication plugin, you can do so by:
1. Log in as root to mysql
2. Run this sql command:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password
BY 'password';  

Replace ‘password’ with your root password. In case your application does not log in to your database with the root user, replace the ‘root’ user in the above command with the user that your application uses.

Digital ocean expounds some more on this here Installing Mysql

answered Dec 21, 2018 at 8:09

Elias Gikonyo's user avatar

8

You have to change MySQL settings.
Edit my.cnf file and put this setting in mysqld section:

[mysqld]
default_authentication_plugin= mysql_native_password

Then run following command:

FLUSH PRIVILEGES;

Above command will bring into effect the changes of default authentication mechanism.

George's user avatar

George

6,7393 gold badges43 silver badges56 bronze badges

answered Sep 17, 2018 at 9:18

michail_w's user avatar

michail_wmichail_w

4,2434 gold badges26 silver badges43 bronze badges

10

I’ve tried a lot of other solutions, but only this works for me.

Thanks for the workaround.

Check your .env

MYSQL_VERSION=latest

Then type this command

$ docker-compose exec mysql bash
$ mysql -u root -p 

(login as root)

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'default'@'%' IDENTIFIED WITH mysql_native_password BY 'secret';

Then go to phpmyadmin and login as :

  • host -> mysql
  • user -> root
  • password -> root

starball's user avatar

starball

14.8k6 gold badges26 silver badges127 bronze badges

answered Dec 23, 2018 at 17:38

Francesco Taioli's user avatar

Francesco TaioliFrancesco Taioli

2,6471 gold badge19 silver badges34 bronze badges

11

None of the answers here worked for me. What I had to do is:

  1. Re-run the installer.
  2. Select the quick action ‘re-configure’ next to product ‘MySQL Server’
  3. Go through the options till you reach Authentication Method and select ‘Use Legacy Authentication Method’

After that it works fine.

answered May 12, 2019 at 12:11

Stuperfied's user avatar

StuperfiedStuperfied

3222 silver badges10 bronze badges

3

Faced the same problem, I was not able to run wordpress docker container with mysql version 8 as its default authentication mechanism is caching_sha2_password instead of mysql_native_password.

In order to fix this problem we must reset default authentication mechanism to mysql_native_password.

Find my.cnf file in your mysql installation, usually on a linux machine it is at the following location — /etc/mysql

Edit my.cnf file and add following line just under heading [mysqld]

default_authentication_plugin= mysql_native_password

Save the file then log into mysql command line using root user

run command FLUSH PRIVILEGES;

answered Apr 21, 2019 at 18:03

Shivinder Singh's user avatar

1

I’m using Laravel Lumen to build a small application.
For me it was because I didn’t had the DB_USERNAME defined in my .env file.

DB_USERNAME=root

Setting this solved my problem.

answered Feb 23, 2019 at 16:12

CIRCLE's user avatar

CIRCLECIRCLE

4,4405 gold badges36 silver badges56 bronze badges

In my.cnf file check below 2 steps.

  • check this value —

    old_passwords=0;

    it should be 0.

  • check this also-

    [mysqld] default_authentication_plugin= mysql_native_password Another
    value to check is to make sure

    [mysqld] section should be like this.

answered Feb 24, 2019 at 5:01

sanjaya's user avatar

sanjayasanjaya

1942 gold badges3 silver badges11 bronze badges

2

preferences -> mysql -> initialize database -> use legacy password encryption(instead of strong) -> entered same password

as my config.inc.php file, restarted the apache server and it worked. I was still suspicious about it so I stopped the apache and mysql server and started them again and now it’s working.

answered Apr 17, 2019 at 7:17

Tăng View Youtube - BUYFAN.NET's user avatar

0

John on October 22, 2021

The default MySQL 8 auth plugin is auth_socket, which causes the error «SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client» when an application is attempting to log in to the database with a password. Let’s go through the steps to fix this.

Step 1

Login to the mysql server in sudo mode as the root user and supply any required passwords.

sudo mysql -u root -p

Step 2

Now run the following ALTER USER command, replacing root with your database user and password if your password.

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

Now run:

FLUSH PRIVILEGES;

Now exit the MySQL server:

exit;

Step 3

You may need to restart the mysql services for the changes to take effect:

sudo service mysql restart

It seems as if with PHP 7.4 the issue is solved.

The following minimalist Docker set up does the trick without even touching the configuration in my.cnf.

docker-compose.yml:

version: "3.6"

services:
  php_fpm:
      build: .
      container_name: cheetah_php_fpm
      working_dir: /cheetah
      volumes:
          - .:/cheetah
          - ./docker/php/php.ini:/usr/local/etc/php/php.ini

  mysql:
      image: mysql:8.0
      container_name: cheetah_mysql
      volumes:
          - ./docker/mysql/conf.d/mysql.cnf:/etc/mysql/conf.d/mysql.cnf
      ports:
          - "3306:3306"
      environment:
          - MYSQL_DATABASE=${DB_DATABASE}
          - MYSQL_ROOT_PASSWORD=${DB_PASSWORD}

Dockerfile:

FROM php:7.4-fpm

RUN apt-get update && apt-get install -y 
    git

RUN docker-php-ext-install pdo_mysql

RUN curl --silent --show-error https://getcomposer.org/installer | php && 
    mv composer.phar /usr/local/bin/composer

RUN pecl install mailparse

docker/mysql/conf.d/mysql.cnf:

# Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0,
# as published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# but not limited to OpenSSL) that is licensed under separate terms,
# as designated in a particular file or component or in included license
# documentation.  The authors of MySQL hereby grant you an additional
# permission to link the program and your derivative works with the
# separately licensed software that they have included with MySQL.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License, version 2.0, for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA

#
# The MySQL  Client configuration file.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

[mysql]

I am a newbie in MySQL, Apache, PHP, and phpMyAdmin. The first server I built was on Windows Vista x32bit and it was successful. Then, I try to build the second server on another laptop, it is Windows 7 x64bit and it stucked in error code #2054. I use ‘localhost’ with a fixed IP address. I installed the server individually from .msi files, NOT a package installer.

After I enter my ‘root’ and my ‘password’, then I clicked ‘Go’, it popped up two error messages, one is «#2054 Cannot log in to the MySQL server» and another is «Connection for controluser as defined in your configuration failed.»

I searched many resources online, but out of luck.

How can I solve these two errors?

Any info in helpful. Thanks in advance.

Below is my config.inc.php:

enter code here <?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * phpMyAdmin sample configuration, you can use it as base for
 * manual configuration. For easier setup you can use setup/
 *
 * All directives are explained in Documentation.html and on phpMyAdmin
 * wiki <http://wiki.phpmyadmin.net>.
 *
 * @package PhpMyAdmin
 */

 /*
  * This is needed for cookie based authentication to encrypt password in
  * cookie
  */
 $cfg['blowfish_secret'] = 'a8b7c6d'; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */

 /*
  * Servers configuration
  */
 $i = 0;

 /*
  * First server
  */
 $i++;
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'cookie';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;

/*
 * phpMyAdmin configuration storage settings.
 */

/* User used to manipulate with storage */
// $cfg['Servers'][$i]['controlhost'] = '';
$cfg['Servers'][$i]['controluser'] = 'phpmyadmin';
$cfg['Servers'][$i]['controlpass'] = 'johan1234';

/* Storage database and tables */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][$i]['relation'] = 'pma_relation';
$cfg['Servers'][$i]['table_info'] = 'pma_table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma_column_info';
$cfg['Servers'][$i]['history'] = 'pma_history';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma_table_uiprefs';
$cfg['Servers'][$i]['tracking'] = 'pma_tracking';
$cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
$cfg['Servers'][$i]['userconfig'] = 'pma_userconfig';
$cfg['Servers'][$i]['recent'] = 'pma_recent';
/* Contrib / Swekey authentication */
// $cfg['Servers'][$i]['auth_swekey_config'] = '/etc/swekey-pma.conf';

/*
 * End of servers configuration
 */

/*
 * Directories for saving/loading files from server
 */
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';

/**
 * Defines whether a user should be displayed a "show all (records)"
 * button in browse mode or not.
 * default = false
 */
//$cfg['ShowAll'] = true;

/**
 * Number of rows displayed when browsing a result set. If the result
 * set contains more rows, "Previous" and "Next".
 * default = 30
 */
//$cfg['MaxRows'] = 50;

/**
 * Use graphically less intense menu tabs
 * default = false
 */
//$cfg['LightTabs'] = true;

/**
 * disallow editing of binary fields
 * valid values are:
 *   false  allow editing
 *   'blob' allow editing except for BLOB fields
 *   'all'  disallow editing
 * default = blob
 */
//$cfg['ProtectBinary'] = 'false';

/**
 * Default language to use, if not browser-defined or user-defined
 * (you find all languages in the locale folder)
 * uncomment the desired line:
 * default = 'en'
 */
//$cfg['DefaultLang'] = 'en';
//$cfg['DefaultLang'] = 'de';

/**
 * default display direction (horizontal|vertical|horizontalflipped)
 */
//$cfg['DefaultDisplay'] = 'vertical';


/**
 * How many columns should be used for table display of a database?
 * (a value larger than 1 results in some information being hidden)
 * default = 1
 */
//$cfg['PropertiesNumColumns'] = 2;

/**
 * Set to true if you want DB-based query history.If false, this utilizes
 * JS-routines to display query history (lost by window close)
 *
 * This requires configuration storage enabled, see above.
 * default = false
 */
//$cfg['QueryHistoryDB'] = true;

/**
 * When using DB-based query history, how many entries should be kept?
 *
 * default = 25
 */
//$cfg['QueryHistoryMax'] = 100;

/*
 * You can find more configuration options in Documentation.html
 * or here: http://wiki.phpmyadmin.net/pma/Config
 */
?>

Learn how to solve the PDO Connection Error: SQLSTATE[HY000] [2054] Server sent charset unknown to the client.

This exception showed up recently when dockerizing an old PHP 5.6 application that uses MySQL as RDBMS. Initially configuring PHP to work with the proper extensions was already a headache because some extensions were old and needed to be compiled from source and so on, so when I finally solved the problem of the extensions, the SQLSTATE[HY000] [2054] error appeared in my screen.

This problem appears basically because you’re using an application that uses a default charset that isn’t the default one anymore in MySQL 8. In my case, my PHP 5.6 application was connecting to the database using utf8 and by default on MySQL 8, the default charset is automatically set to utf8mb4 and therefore, the exception appears because the client application doesn’t understand what the server means and throws the mentioned error.

In this article, I will propose you 2 possible solutions for this problem when trying to connect to your database.

Solution #1 (Adjust default character set)

By default, in MySQL 8 the default charset is set to utf8mb4, which is usually not compatible with old clients, just like in my case with a Symfony 1.4 project. If you want to provide compatibility with MySQL 8, you will need to adjust the default character set of your MySQL instance through the configuration file. Find the configuration file of MySQL (usually located in /etc/my.cnf or /etc/mysql/conf.d/my.cnf) and add the following settings in the mentioned sections:

# /etc/mysql/conf.d/my.cnf

[mysqld]

collation-server = utf8_unicode_ci
character-set-server = utf8 

# Otherwise the following exception will be thrown: the server requested authentication method unknown to the client
default_authentication_plugin= mysql_native_password

[client] 
default-character-set=utf8 

[mysql]
default-character-set=utf8

After updating the configuration file of MySQL, be sure to update the authentication plugin used for your users. In this case, I’m using the root user to connect to the database, So i’ll update specifically that user only:

--- Update the authentication plugin of the user e.g for root with the password ---
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'yourRootPassword';
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'yourRootPassword';
ALTER USER 'default'@'%' IDENTIFIED WITH mysql_native_password BY 'yourRootPassword';

--- Then flush the privileges ---
FLUSH PRIVILEGES;

Finally restart the mysql service (or container in case that you’re using docker):

sudo service mysql restart

And that’s it! Your application should be able to connect now assuming that the old charset was UTF-8.

Solution #2 (Downgrade MySQL)

This was the solution for me since, it wasn’t possible to use MySQL 8 in the old project, so I had to simply use MySQL 5.7 instead. Downgrading automatically removed every of the new exceptions that I never saw when configuring the project as usual. The original RDBMS for this project was MySQL 5.7, so that solved every incompatibility.

Happy coding ❤️!

PHP must be expecting to use the old MySQL authentication plugin algorithms. You do not have to restart mysql. Since old_passwords is a globally dynamic option, all you have to do is run the following:

SET GLOBAL old_passwords = 1;

In addition, please add this to /etc/my.cnf:

[mysqld]
old_passwords=1

to have future restarts retain this setting.

To further verify the need to do this, the next time you login to mysql, run this

SELECT LENGTH(password) password_length,COUNT(1) length_count
FROM mysql.user GROUP BY LENGTH(password);

If none of the passwords are of length 16, this may explain PHP’s reluctance to login.

Sad to say, but the alternative would be to setup 16-character passwords, but you cannot reverse-engineer 41-character passwords. You would have to manually setup the 16-character passwords using the original plain-text values.

For example, if root@localhost had ‘helloworld’ as the password, it would have convert it using the OLD_PASSWORD function. Here is a comparison:

mysql> select password('helloworld');
+-------------------------------------------+
| password('helloworld')                    |
+-------------------------------------------+
| *D35DB127DB631E6E27C6B75E8D376B04F64FAF83 |
+-------------------------------------------+
1 row in set (0.00 sec)

mysql> select old_password('helloworld');
+----------------------------+
| old_password('helloworld') |
+----------------------------+
| 6c755a9e66debe8a           |
+----------------------------+
1 row in set (0.00 sec)

mysql>

Once you activate old_passwords, to convert it you would have to do something like this:

UPDATE mysql.user
SET password = OLD_PASSWORD('helloworld')
WHERE password = PASSWORD('helloworld');
FLUSH PRIVILEGES;

UPDATE 2013-02-02 22:44 EDT

If changing the authentication style on the MySQL side has not worked for you at this point, I have some bad news for you. You stated earlier:

I used php 5.2.9 and everything worked ok but lowering php is not a solution for me. I also have to mention that i dont have full access to DB’s settings cause the client doesn’t give me that full access.

You may need to downgrade PHP after all. If your hosting provider isn’t in position or unwilling to adjust MySQL or give you a downgraded PHP, you will have to go with a hosting provider that will.

As an alternative you may want to look into Amazon EC2 when you can have full control of all software upgrades after running sudo -s. The links you mentioned before gave you what you needed to know. I gave you what you can do to accommodate the MySQL side. Do what you know has to be done to get this solved.

Ошибка аутентификации при подключении к базе данных

Установив на свой компьютер nginx, php7 и MySQL 8 обнаружил, что я не могу подключиться к базам данных через adminer (офигенная легкая альтернатива phpmyadmin), получая сообщение SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client. Ниже как побороть ошибку.

Рис.1. Ошибка аутентификации базы данных

Рис.1. Ошибка аутентификации базы данных

В MySQL 8 была изменена схема хранения пароля, начиная с версии 8.0.4 длина хэша пароля увеличена до максимального (255 символов), а также изменили плагин аутентификации – вместо mysql_native_password используется caching_sha2_password. Потому, авторизоваться паролем, который был создан для root при установке базы данных, не получиться. Пароль пользователя надо обновить. Небольшой парадокс — для того, чтобы обновить пароль, с которым ты не можешь авторизоваться, нужно сначала авторизоваться 🙂 Как это сделать?

Первый вариант – использовать MySQL Workbench, которая идет в комплекте с MySQL. Она пускает по установленному паролю. В программе нужно откорыть окно создания нового запроса и ввести команду обновления пароля для root:

ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘newpassword’;

Рис.2. Обновление пароля root через MySQL Workbench

Рис.2. Обновление пароля root через MySQL Workbench

Второй вариант – если не установлен MySQL Workbench, можно запустить командную строку MySQL и там ввести ту же команду. При запуске консоли MySQL будет запрошен пароль root’а.

ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘newpassword’;

Рис.3. Обновление пароля root через консоль MySQL

Рис.3. Обновление пароля root через консоль MySQL


No comments yet.

Понравилась статья? Поделить с друзьями:
  • Mysql ошибка 1698
  • Mysql ошибка 1406
  • Navien deluxe s ошибка 03 пламя есть
  • Navien deluxe nr 15s ошибка 10
  • Navien deluxe coaxial 30k ошибка 03