On this page
- How do MySQL accounts work?
- How do you create a user and grant least privilege?
- How do you group privileges with roles?
- How do you enforce password strength?
- How do you set expiry, history and lockout rules?
- How do you rotate an application password without downtime?
- How do you require TLS and limit resources?
- How do you audit, revoke and remove accounts?
- Questions
How do MySQL accounts work?
An account is a user name plus a host part, written 'name'@'host', and the server picks the most specific match for every incoming connection. 'shop'@'localhost' and 'shop'@'%' are two different accounts with separate passwords and rights.
Common host parts:
localhost: connections over the Unix socket or from 127.0.0.1 on the same server, which covers most web apps and SSH tunnels.198.51.100.24: one fixed remote address, for an app server that connects over a private link.10.8.0.%: a subnet, for example a WireGuard network.%: anywhere. Avoid it on a server with a public IP.
Everything in this guide works on MySQL 8.0 and 8.4 and on MariaDB 10.11 and newer, with the differences called out. Log in as the administrator with sudo mysql or sudo mariadb; the install guides for MySQL and MariaDB set that up.
How do you create a user and grant least privilege?
Create the account, then grant the smallest set of statements the application uses, on its own database only. Most web apps need just four data statements plus schema rights during installs and upgrades.
CREATE DATABASE shop CHARACTER SET utf8mb4;
CREATE USER 'shop'@'localhost' IDENTIFIED BY 'Long-Random-Passphrase-12';
GRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO 'shop'@'localhost';
-- only while the app runs migrations:
GRANT CREATE, ALTER, INDEX, DROP, REFERENCES ON shop.* TO 'shop'@'localhost';
SHOW GRANTS FOR 'shop'@'localhost';No FLUSH PRIVILEGES is needed after CREATE USER or GRANT; the server applies them at once. Rights can be narrower still: GRANT SELECT ON shop.orders for a single table, or GRANT SELECT (id, total) ON shop.orders for chosen columns.
On MySQL 8, let the server generate a strong secret and print it once:
CREATE USER 'report'@'localhost' IDENTIFIED BY RANDOM PASSWORD;Never hand an application ALL PRIVILEGES ON *.* or the GRANT OPTION; a bug in that app would then own every database on the server.
How do you group privileges with roles?
Create a role per job (read only, read and write, admin of one schema), grant rights to the role, then grant the role to users. Changing a role changes every member at once.
MySQL 8
CREATE ROLE 'shop_read', 'shop_write';
GRANT SELECT ON shop.* TO 'shop_read';
GRANT INSERT, UPDATE, DELETE ON shop.* TO 'shop_write';
CREATE USER 'alice'@'localhost' IDENTIFIED BY 'Another-Long-Secret-8';
GRANT 'shop_read', 'shop_write' TO 'alice'@'localhost';
SET DEFAULT ROLE ALL TO 'alice'@'localhost';MySQL roles are inactive in a session until they are set as default roles or activated with SET ROLE. If you prefer every granted role to be active at login, set SET PERSIST activate_all_roles_on_login = ON;. Check with SELECT CURRENT_ROLE();.
MariaDB
CREATE ROLE shop_read;
GRANT SELECT ON shop.* TO shop_read;
GRANT shop_read TO 'alice'@'localhost';
SET DEFAULT ROLE shop_read FOR 'alice'@'localhost';MariaDB role names have no host part, and a user has one default role at a time; roles can be granted to other roles to build a hierarchy.
How do you enforce password strength?
On MySQL install the validate_password component; on MariaDB load the simple_password_check plugin. Both reject weak passwords at CREATE USER and ALTER USER time.
MySQL 8
INSTALL COMPONENT 'file://component_validate_password';
SET PERSIST validate_password.policy = 'STRONG';
SET PERSIST validate_password.length = 14;
SHOW VARIABLES LIKE 'validate_password%';The STRONG policy demands mixed case, digits, special characters and no dictionary words when a dictionary file is set. SET PERSIST writes the values to mysqld-auto.cnf, so they survive a restart.
MariaDB
INSTALL SONAME 'simple_password_check';
SET GLOBAL simple_password_check_minimal_length = 14;
INSTALL SONAME 'password_reuse_check';
SET GLOBAL password_reuse_check_interval = 365;Put the MariaDB values in a config file under [mariadb] as well, since SET GLOBAL lasts only until the next restart. The reuse check stops people from recycling an old password within the interval.
How do you set expiry, history and lockout rules?
Attach the rules to each human account with ALTER USER. Application accounts usually skip expiry, because a password that expires at night takes the site down.
-- MySQL 8
ALTER USER 'alice'@'localhost'
PASSWORD EXPIRE INTERVAL 180 DAY
PASSWORD HISTORY 5
PASSWORD REUSE INTERVAL 365 DAY
FAILED_LOGIN_ATTEMPTS 5 PASSWORD_LOCK_TIME 1;
ALTER USER 'shop'@'localhost' PASSWORD EXPIRE NEVER;After five wrong passwords in a row, the account locks for one day; an administrator can unlock it early with ALTER USER ... ACCOUNT UNLOCK. A server-wide default for expiry is default_password_lifetime.
MariaDB supports PASSWORD EXPIRE INTERVAL n DAY per account and default_password_lifetime globally. For lockout it uses the global max_password_errors setting: an account that exceeds it is blocked from new connections until an administrator runs FLUSH PRIVILEGES.
Lock an account without deleting it, for example while someone is away:
ALTER USER 'alice'@'localhost' ACCOUNT LOCK;How do you rotate an application password without downtime?
MySQL 8 supports dual passwords: set the new one while keeping the old, update every app server, then discard the old secret.
ALTER USER 'shop'@'localhost' IDENTIFIED BY 'New-Long-Secret-2027' RETAIN CURRENT PASSWORD;
-- deploy the new secret to every app instance, then:
ALTER USER 'shop'@'localhost' DISCARD OLD PASSWORD;MariaDB has no dual passwords. The usual workaround is a second account with the same grants, for example shop2: switch the app to it, then change or drop the first one. Keep secrets out of shell history by typing them in the client prompt or reading them from a file that only the service user can open. On the authentication side, MySQL uses caching_sha2_password by default; MariaDB can use the stronger ed25519 plugin with INSTALL SONAME 'auth_ed25519' and IDENTIFIED VIA ed25519 USING PASSWORD('...') where clients support it.
How do you require TLS and limit resources?
Add REQUIRE SSL to accounts that connect over a network, and resource limits to accounts that could be abused.
CREATE USER 'shop'@'10.8.0.%' IDENTIFIED BY 'Remote-Secret-Value-4' REQUIRE SSL;
GRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO 'shop'@'10.8.0.%';
ALTER USER 'report'@'localhost' WITH MAX_USER_CONNECTIONS 5 MAX_QUERIES_PER_HOUR 5000;MySQL 8 creates self-signed TLS certificates on first start, so REQUIRE SSL works out of the box. MariaDB needs certificates set with ssl_cert and ssl_key in the server config; recent MariaDB 11 releases can also generate them automatically. For remote access patterns that avoid opening port 3306 altogether, read remote database access.
How do you audit, revoke and remove accounts?
List accounts regularly, revoke rights no longer needed and drop accounts nobody uses. A short review every quarter keeps the list honest.
SELECT user, host FROM mysql.user ORDER BY user;
-- MySQL 8 extra detail
SELECT user, host, account_locked, password_last_changed FROM mysql.user;
SHOW GRANTS FOR 'alice'@'localhost';
REVOKE INSERT, UPDATE, DELETE ON shop.* FROM 'alice'@'localhost';
RENAME USER 'old'@'localhost' TO 'old_disabled'@'localhost';
DROP USER 'old_disabled'@'localhost';Look for anonymous users (an empty user name), accounts with host %, and any user other than the administrator holding SUPER or global ALL PRIVILEGES. If an app fails after a change, the error names the missing privilege, for example INSERT command denied; grant exactly that. Remember that a dump of databases does not include accounts: back up and restore MySQL shows how to save them.
Questions about MySQL users, roles and passwords
Do I need FLUSH PRIVILEGES after GRANT?
No. GRANT, REVOKE, CREATE USER and ALTER USER take effect immediately. It is only needed after editing the grant tables directly, which you should avoid.
Why does my user get access denied from localhost?
Usually an anonymous account or a different host part matches first, or the app connects over TCP to 127.0.0.1 while the account was made for another host. Check SELECT USER(), CURRENT_USER(); to see which account matched.
Can one user have different passwords from different hosts?
Yes, because 'app'@'localhost' and 'app'@'10.8.0.%' are separate accounts. Keep them in sync or give them clearly different names.
What privileges does WordPress need?
For daily use, SELECT, INSERT, UPDATE and DELETE on its database. Core and plugin updates also run CREATE, ALTER, INDEX and DROP, so most people grant those on the WordPress database only.
Are MySQL roles and MariaDB roles the same?
The idea is the same, but the syntax differs: MySQL role names have a host part and several default roles, MariaDB roles have no host and one default role per user.
More in Databases
- Install MySQL 8
- Install MariaDB
- Install PostgreSQL
- Install MongoDB
- PostgreSQL JSON, arrays and special types
- PostgreSQL views, triggers and CTEs
- PostgreSQL full-text search and encryption
- MySQL keys, indexes and full-text search
- MySQL JSON, views and stored procedures
- Apache Solr search server
- Install Redis or Valkey
- Install Memcached
- Apache Cassandra cluster
- Install Apache CouchDB
- InfluxDB for time series
- Install Elasticsearch
- Back up and restore MySQL and MariaDB
- Back up and restore PostgreSQL
- PostgreSQL roles and permissions
- Repair a crashed MySQL table
- PostgreSQL streaming replication
- MongoDB replica set
- PostGIS for location data
- Database insight with PgHero
- Couchbase Server
- ArangoDB multi-model database
- Remote database access over SSH