Users and Permissions: Why Your App Should Not Log In as Admin
When you install PostgreSQL or MySQL, you get a powerful administrator account. It is tempting to use it for everything, including your app. This page explains why that is risky and how to create a limited user instead.
Users and permissions in one paragraph
Server databases have users (PostgreSQL also calls them roles). Each user has permissions that say what it may do: read certain tables, change them, create new ones, or manage other users. The administrator, such as postgres in PostgreSQL or root in MySQL, may do everything.
Why the app should have its own, limited user
Imagine a bug, or an attacker exploiting SQL injection, makes your app run a harmful command. What happens depends on the permissions of the account the app uses:
| App logs in as... | A harmful DROP TABLE would... |
|---|---|
| Administrator | Succeed, along with anything else |
| A limited user who can only read and write its tables | Fail |
This idea is called the principle of least privilege: give each account only the permissions it needs.
Creating a limited user in PostgreSQL
CREATE ROLE notes_app WITH LOGIN PASSWORD 'choose-a-strong-one';
GRANT CONNECT ON DATABASE practice TO notes_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON notes TO notes_app;
The app can now work with the notes table but cannot drop it or create new tables. Depending on how your tables were created, you may also need GRANT USAGE ON SCHEMA public TO notes_app; and permission on the sequence behind an auto-numbered id; the PostgreSQL documentation on privileges explains the details.
Creating a limited user in MySQL
CREATE USER 'notes_app'@'localhost' IDENTIFIED BY 'choose-a-strong-one';
GRANT SELECT, INSERT, UPDATE, DELETE ON practice.notes TO 'notes_app'@'localhost';
The @'localhost' part says this user may only connect from the same computer.
What about schema changes?
Creating and altering tables is usually done by a separate account during migrations, not by the running app. In small practice projects you can use the administrator for migrations and the limited user for the app.
SQLite is different
SQLite has no users or permissions. Anyone who can read the file can read the data. Protect SQLite files with ordinary file permissions, and do not put them where a web server could serve them as downloads.
A checklist
- [ ] The app connects with its own user, not the administrator.
- [ ] That user has only the permissions it needs.
- [ ] Its password is stored outside code, in an environment variable.
- [ ] Administrator passwords are known only to the people who need them.
Where next
Limited permissions are a second line of defence; the first is using placeholders in every query. See SQL injection: short questions, plain answers.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.