How to disable MySQL root logins when no password is supplied?

a coder picture a coder · Aug 24, 2011 · Viewed 31.6k times · Source

MySQL is installed on my laptop and it works fine, except that I am allowed to log in without supplying the root password. I can also log in by supplying the root password. If the supplied password doesn't match, it denies access. The root password was changed to something of my own choosing when I originally installed MySQL. I just noticed the no-password logins today.

So, I need to stop access to the root account when a password isn't supplied. What I've tried so far is to reset the root password with:

mysqladmin -u root password TopSecretPassword

I then logged in to the console and issued:

mysql> flush privileges;  exit;

I'm still able to log in to MySQL with:

%> mysql -u  {enter}

How do I stop this behavior?

ADDITIONAL DETAILS:

%> mysql -u  {enter}

mysql>SELECT USER(), CURRENT_USER();
> root@localhost, root@localhost

mysql>SELECT COUNT(*) FROM mysql.users WHERE user='root' AND password='';
> COUNT(*)
> 0

mysql>SELECT COUNT(*) FROM mysql.users WHERE user='';
> COUNT(*)
> 0

mysql>SELECT COUNT(*) FROM mysql.users WHERE user='root';
> COUNT(*)
> 1

%> vi /etc/my.cnf
/skip-grant-tables
> E486: Pattern not found: skip-grant-tables

Answer

Jeremy Davis picture Jeremy Davis · Feb 22, 2018

Users encountering this behaviour in newer versions of MySQL/MariaDB (e.g. Debian Stretch, etc) should be aware that in the mysql.user table, there is column called 'plugin'. If the 'unix_socket' plugin is enabled, then root will be able to log in via commandline without requiring a password. Other log in mechanisms will be disabled.

To check if that's the case:

SELECT host, user, password, plugin FROM mysql.user;

which should return something like this (with unix_socket enabled):

+-----------+------+--------------------------+-------------+
| host      | user | password                 | plugin      |
+-----------+------+--------------------------+-------------+
| localhost | root | <redacted_password_hash> | unix_socket |
+-----------+------+--------------------------+-------------+

To disable that and require root to use a password:

UPDATE mysql.user SET plugin = '' WHERE user = 'root' AND host = 'localhost';
FLUSH PRIVILEGES;

Note: As noted by @marioivangf (in a comment) in newer versions of MySQL (e.g. 5.7.x) you may need to set the plugin to 'mysql_native_password' (rather than blank).

Then restart:

service mysql restart

Problem fixed!:

root@lamp ~# mysql
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Source: https://stackoverflow.com/a/44301734/3363571 Big thanks to @SakuraKinomoto (please go up vote his answer if you find this useful).