Skip to the fix
PHPSolvedThe fix first, then the reason

Newest fixes

Radovan Sykora in MySQL | | 7 min

MySQL error 1045 (28000) access denied for user: what it is telling you

Error 1045 names the user, the host the server saw and whether a password was sent. Read those three parts first and you know which fix applies.

Old brass keys beside a closed padlock on slate
On this page
  1. Reproduce it with two accounts
  2. Which account wins when several match
  3. localhost is not 127.0.0.1
  4. Ubuntu and Debian: root without a password
  5. Passwords with special characters
  6. using password: NO from an application
  7. caching_sha2_password and old programs
  8. It says 1044, not 1045
  9. Resetting root when nothing else works

The message contains three facts, and each one rules out half of the usual advice:

output
ERROR 1045 (28000): Access denied for user 'shopapp'@'localhost' (using password: YES)
  • 'shopapp' is the name your program sent. If that's not the name you configured, the configuration isn't being read.
  • 'localhost' is where the server thinks you came from. It is not the server's own address.
  • using password: YES says that a password was sent, not that it was right. NO means none arrived at all.
What you seeStart with
using password: NO, and you set oneThe password variable is empty, or the option file isn't read
using password: YES from your program, works in a consoleSpecial characters, or a different host or socket
using password: YES everywhereWrong password, or no account for that host
The part in brackets is missingError 1698: the account uses a socket plugin
Code 1044 instead of 1045The login worked, the database privilege is missing
Host ... is not allowed to connectNo account at all for that host

The server doesn't reveal whether the account exists. A wrong password and an unknown user name produce the same text, so the message can't confirm a typo in the name.

Reproduce it with two accounts

Account names in MySQL have two halves, and 'shopapp'@'localhost' and 'shopapp'@'127.0.0.1' are different accounts with separate passwords. This creates one account of each kind, plus one that may come from anywhere:

sqlran on MySQL 8.0.33
DROP USER IF EXISTS 'lab_1045_a'@'localhost', 'lab_1045_b'@'127.0.0.1', 'lab_1045_c'@'%';
CREATE USER 'lab_1045_a'@'localhost' IDENTIFIED BY 'p#ss$word1';
CREATE USER 'lab_1045_b'@'127.0.0.1' IDENTIFIED BY 'second';
CREATE USER 'lab_1045_c'@'%' IDENTIFIED BY 'third';

Now connect with each of them over the socket, and the last two over TCP:

phpran on PHP 8.2.8
<?php
$socket = getenv('LAB_SOCKET') ?: null;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$port = (int) (new mysqli('localhost', 'root', '', '', null, $socket))
    ->query('SELECT @@port')->fetch_row()[0];

$tries = [
    ['localhost', 'lab_1045_a', ''],
    ['localhost', 'lab_1045_a', 'wrong'],
    ['localhost', 'lab_1045_nobody', 'x'],
    ['localhost', 'lab_1045_b', 'second'],
    ['127.0.0.1', 'lab_1045_b', 'second'],
    ['localhost', 'lab_1045_c', 'third'],
];
foreach ($tries as [$host, $user, $pass]) {
    try {
        $db = $host === 'localhost'
            ? new mysqli($host, $user, $pass, '', null, $socket)
            : new mysqli($host, $user, $pass, '', $port);
        [$sent, $used] = $db->query('SELECT USER(), CURRENT_USER()')->fetch_row();
        echo "OK   $sent authenticated as $used\n";
    } catch (mysqli_sql_exception $e) {
        echo $e->getCode(), ' ', $e->getMessage(), "\n";
    }
}
real output
1045 Access denied for user 'lab_1045_a'@'localhost' (using password: NO)
1045 Access denied for user 'lab_1045_a'@'localhost' (using password: YES)
1045 Access denied for user 'lab_1045_nobody'@'localhost' (using password: YES)
1045 Access denied for user 'lab_1045_b'@'localhost' (using password: YES)
OK   lab_1045_b@localhost authenticated as lab_1045_b@127.0.0.1
OK   lab_1045_c@localhost authenticated as lab_1045_c@%

The fourth line is the one that costs people an afternoon. The user name is right, the password is right, and the login fails, because over the socket the server sees localhost and there's no lab_1045_b account for it.

The fifth line is stranger. The connection came in over TCP, yet USER() reports lab_1045_b@localhost. The server resolved 127.0.0.1 back to a name, and it matches accounts against the address as well as the name. So localhost in an error message doesn't prove that a socket was used. On a server with skip_name_resolve turned on there's no lookup, and then only the address counts. Comparing the two functions, USER() for what you asked for and CURRENT_USER() for the account that answered, is the quickest way to see which row won.

Which account wins when several match

The server sorts the accounts before it looks: the most specific host first, and for equal hosts a named user before a blank one. It takes the first row that matches both host and name, and it doesn't try the next row if the password fails. The manual describes the order under access control, connection verification.

That rule makes an anonymous account on localhost dangerous. With ''@'localhost' present, lab_1045_c, which only exists for %, can no longer log in locally with its password. The anonymous row has the more specific host, so it's tried first and expects no password. The answer is 1045 with using password: YES. Without a password the same login succeeds, as nobody:

output
user()                  current_user()
lab_1045_c@localhost    @localhost

List what you have, and look for blank names and for the same name on several hosts:

sql
SELECT user, host, plugin, account_locked
FROM mysql.user ORDER BY user, host;

If a blank user is listed and no one needs it, note its privileges with SHOW GRANTS FOR ''@'localhost' and then remove it with DROP USER ''@'localhost'. The other repair is the one the manual recommends: add an account for localhost next to the one for %.

localhost is not 127.0.0.1

With localhost, MySQL programs and PHP's mysqli use the Unix socket file. With 127.0.0.1 they use TCP. The two can even end up on different servers, when a system package and a Docker container or XAMPP are both running. Before changing any password, ask the server that works which one it is:

sql
SELECT @@hostname, @@port, @@socket, @@version;

Then compare with the settings in your application. A host of localhost with a port number is a warning sign: the port is ignored and the socket is used.

Ubuntu and Debian: root without a password

On Ubuntu's MySQL package, root logs in through a plugin called auth_socket. Ubuntu's server documentation says that no password is required because of it, and shows the login:

bash
sudo mysql -u root

The plugin asks the operating system who is running the program, and only the system user of the same name gets in. MySQL's own page on socket authentication explains the mechanism. Any password you type is ignored, and a web application running as www-data can't become root. Refused logins of this sort carry the code 1698, whose text in the error reference ends after the host, without the bracket about passwords. MariaDB has the same arrangement under the name unix_socket, and its page says root@localhost uses it by default.

Don't switch root to a password to please an application. Give the application its own account:

sql
CREATE USER 'shopapp'@'localhost' IDENTIFIED BY 'a long random password';
GRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO 'shopapp'@'localhost';

The same goes for phpMyAdmin, which has no accounts of its own and passes your login straight to MySQL. The localhost/phpmyadmin checks cover that screen.

Passwords with special characters

A shell reads the password before MySQL does. With the password p#ss$word1, double quotes let the shell replace $word1 with an empty variable, and the server receives p#ss:

bashran in bash
printf '%s\n' "p#ss$word1" 'p#ss$word1'
real output
p#ss
p#ss$word1

Use single quotes, or better, -p with nothing after it and type the password at the prompt. Mind the space too: in mysql -u root -p secret, the word secret is taken as the name of a database, and the program still asks for a password.

Option files have their own rule. # starts a comment, even in the middle of a line. This file sends the password p:

ini
[client]
user=lab_1045_a
password=p#ss$word1

With that file the login failed, and with password="p#ss$word1" in quotes it worked. The manual mentions exactly this use of quotes on its page about option files. Option files are also why a password you never typed may be sent: using password: YES on a bare mysql command means a file has one. mysql --no-defaults -u root ignores them all, and mysql --print-defaults shows what was collected, with the password masked.

In a PHP file, double quotes cause the shell's problem again, since "p#ss$word1" is interpolated. If your framework reads a .env file, quote the value there as well.

using password: NO from an application

When a console login works and the application reports NO, the password got lost before the connection was made. The variable is undefined, the environment file isn't loaded in this process, or the value belongs to a different key. Print what the code has, without printing the secret itself, right before it connects:

phpran on PHP 8.2.8
<?php
$password = getenv('DB_PASSWORD');
var_dump($password === false, is_string($password) ? strlen($password) : null);
real output
bool(true)
NULL

true means that the variable doesn't exist in this process at all. A length one higher than expected usually means a newline at the end, from a secret file that was read without trim().

caching_sha2_password and old programs

MySQL 8.0 creates accounts with the caching_sha2_password plugin. Programs that don't know it fail with other messages (for example 1251, "Client does not support authentication protocol requested by server"), so 1045 normally isn't about the plugin. One effect does look random: a TCP connection without TLS works at first and later fails with 2061, "Authentication requires secure connection". The full exchange of the password needs TLS, a socket, or the server's RSA key. Once a login has succeeded the server keeps a cached entry, and the short exchange is enough. After a password change the cache is empty again. On 8.0.33 the same unencrypted mysql command worked before an ALTER USER, failed right after it, and worked again with --get-server-public-key added.

It says 1044, not 1045

Then you're in. The account and the password are fine, and the database name is the part that was refused:

phpran on PHP 8.2.8
<?php
$socket = getenv('LAB_SOCKET') ?: null;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    new mysqli('localhost', 'lab_1045_a', 'p#ss$word1', 'mysql', null, $socket);
} catch (mysqli_sql_exception $e) {
    echo $e->getCode(), ' ', $e->getMessage(), "\n";
}
real output
1044 Access denied for user 'lab_1045_a'@'localhost' to database 'mysql'

SHOW GRANTS from an administrative account lists what's there. A line with USAGE alone means "may connect, nothing else":

sqlran on MySQL 8.0.33
SHOW GRANTS FOR 'lab_1045_a'@'localhost';
DROP USER 'lab_1045_a'@'localhost', 'lab_1045_b'@'127.0.0.1', 'lab_1045_c'@'%';
real output
+------------------------------------------------+
| Grants for lab_1045_a@localhost                |
+------------------------------------------------+
| GRANT USAGE ON *.* TO `lab_1045_a`@`localhost` |
+------------------------------------------------+

A name with a typo shows up here as well: a user without any privilege on a missing database gets 1044, not "unknown database".

Resetting root when nothing else works

If sudo mysql gets you in, you don't need a reset. Use ALTER USER. Otherwise the manual's reset procedure is the one to follow, and it has two forms.

The preferred one starts the server with an init file. Write a single line into a file that only the mysql system user can read:

sql
ALTER USER 'root'@'localhost' IDENTIFIED BY 'the new password';

Stop the server, start it once with mysqld --init-file=/path/to/that/file, then delete the file and start the service normally. Nobody else gets in while you do it, which is the advantage over the second form.

The second form uses --skip-grant-tables, where everyone who connects has every privilege. MySQL 8.0 turns off remote connections in that mode, but every local account can still get in, so keep it short. FLUSH PRIVILEGES comes first, because ALTER USER is disabled until the grant tables are loaded. After ALTER USER, restart without the option.

A copy of the data directory before either procedure costs a few minutes and covers a slip. So does a dump, if any account still works. A login that works and then drops in the middle of the job is another error, with its own page.

Same subject