After new installation of MySQL with mysql_secure_installation you may find that when you try to login using the root password it refuses. This is because by default you start with unix_socket. It by default allows the root user to enter into MySQL command line without password.

If you try:

$ mysql -uroot -p
Enter password:

It will prompt you enter the password but then it will refuse with an error:

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

Or when you login as root user, you can simply run mysql and it will straight let you into the MySQL command line.

$ sudo mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 40
Server version: 5.7.22-0ubuntu18.04.1 (Ubuntu)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>

Change to unix_socket to password

First let's check to see which authentication plugin that MySQL is using.

mysql> select plugin from mysql.user where User='root';
+-------------+
| plugin      |
+-------------+
| auth_socket |
+-------------+
1 row in set (0.00 sec)

mysql>

To be able to login with password, you have to change the plugin from auth_socket to mysql_native_password. This can be achieved using the following command.

mysql> update mysql.user set plugin='mysql_native_password';
Query OK, 5 rows affected (0.23 sec)
Rows matched: 5  Changed: 5  Warnings: 0

Then set the default password of the root user:

mysql> alter user 'root'@'localhost' identified with mysql_native_password by '<new password>';
Query OK, 0 rows affected (0.18 sec)

Done! That easy

Now you can try:

$mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 23
Server version: 8.0.23-0ubuntu0.20.04.1 (Ubuntu)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Once you enter your password, you can successfully enter using the username and password.