← Back to Error Lab

MySQL: Error 1045 (28000): Access denied for user

Published 2026-04-14

Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.

Root Cause

This is the standard authentication failure error in MySQL. It means the database server rejected the connection attempt. The reasons are straightforward: an incorrect username, an incorrect password, or the user is trying to connect from a host (IP address) that they are not authorized to use. MySQL privileges are tied to both the username and the host (e.g., 'root'@'localhost' is different from 'root'@'%'). A common scenario is trying to connect remotely with a user configured only for localhost access.

Fix / Solution

Verify the username and password in your database connection string or `.env` file. Ensure that the database user actually exists. If connecting remotely, log into MySQL locally and grant the user permissions to connect from `%` (any host) or the specific IP address of your application server. Remember to run `FLUSH PRIVILEGES;` after modifying user permissions.

Code Snippet

-- ❌ Connects locally, but fails remotely if user is 'user'@'localhost'
mysql -u user -p -h remote.server.ip

-- ✅ Grant remote access (Run as root in MySQL)
CREATE USER 'user'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON database_name.* TO 'user'@'%';
FLUSH PRIVILEGES;