Skip to main content
Albero Academy

Security & User Management

Create users, grant least-privilege access with roles, and defend against SQL injection — the non-negotiables of running a database.

Chapter 14MySQL15 min readBeginner friendly
  • #MySQL
  • #Security
  • #Users

A database holds your most valuable asset, so access control isn't optional. This chapter covers creating users, granting only the privileges each one needs, and the single most important application-security rule: never build SQL by string concatenation.

Users & authentication

A MySQL user is name@host — the host limits where they can connect from:

creating users
CREATE USER 'app'@'10.0.0.%' IDENTIFIED BY 'a-strong-password';
CREATE USER 'analyst'@'localhost' IDENTIFIED BY 'another-password';
-- Never run the application as root; make a dedicated, limited user.

GRANT & least privilege

Grant the minimum privileges each user needs on the specific databases/tables — never blanket ALL on *.*:

scoped privileges
-- The app needs to read/write its own database only
GRANT SELECT, INSERT, UPDATE, DELETE ON albero.* TO 'app'@'10.0.0.%';
-- The analyst needs read-only
GRANT SELECT ON albero.* TO 'analyst'@'localhost';
FLUSH PRIVILEGES;
SHOW GRANTS FOR 'app'@'10.0.0.%';

Roles

From MySQL 8, a role bundles privileges you can grant to many users — change the role, change everyone at once:

roles
CREATE ROLE 'read_only';
GRANT SELECT ON albero.* TO 'read_only';
GRANT 'read_only' TO 'analyst'@'localhost'; -- assign the role to a user

SQL injection — the cardinal sin

parameterised (server-side prepared statement)
PREPARE stmt FROM 'SELECT * FROM students WHERE email = ?';
SET @e = 'aanya@example.com';
EXECUTE stmt USING @e; -- the value is data, never executed as SQL
DEALLOCATE PREPARE stmt;

Practice

Create an app user with only CRUD on one database and an analyst with read-only, then verify with SHOW GRANTS. Bundle read-only into a role and assign it. Explain, in one sentence each, why running as root and why string-built SQL are dangerous.

Key takeaways

  1. 01A MySQL user is name@host; the host restricts where they can connect from.
  2. 02Grant least privilege on specific databases/tables — never ALL on *.* except for admins.
  3. 03Roles (MySQL 8+) bundle privileges so you manage many users through one grant.
  4. 04Never build SQL by concatenating input — use parameterised/prepared statements to stop injection.
  5. 05Run the app as a dedicated limited user, never as root.