Course contentsShow
← Node.js
Lesson 992 of 1,9809. Authentication and Identity ManagementFree lesson

The Principle of Least Privilege in Databases

Restrict the application user's DB access to only the tables required for authentication.

In this lesson, you will learn how to harden your application’s database security by restricting the database user account to only the tables strictly necessary for authentication processes.

The Problem: Over-Privileged Connections

In many Node.js applications, we tend to use a single "super-user" database account defined in our DATABASE_URL or environment variables. This account often has full SELECT, INSERT, UPDATE, and DELETE permissions on every table in the schema. If an attacker manages to perform an SQL injection attack via your authentication middleware, they gain access to sensitive tables—like your financial_records or internal_logs—even if those tables have absolutely nothing to do with logging a user in.

The Solution: Scoping the Auth User

To enforce the Principle of Least Privilege, your application should connect to the database using an account that is restricted to the bare minimum. For your authentication flow, the database user should only have permissions on the users table and perhaps a sessions table (or your Redis-backed schema).

Instead of granting ALL PRIVILEGES, you should create a dedicated database role for your auth service:

-- Create a restricted role
CREATE ROLE auth_service;

-- Grant access only to the necessary tables
GRANT SELECT, INSERT, UPDATE ON users TO auth_service;
GRANT SELECT, DELETE ON sessions TO auth_service;

-- Ensure the user cannot touch other sensitive tables
-- Revoke all permissions on the rest of the database
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM auth_service;

In your Node.js code, ensure your database client initializes using these specific credentials. By doing this, even if a vulnerability exists in your login controller, an attacker is "jailed" within the users and sessions tables. They cannot execute DROP TABLE on your product catalog or steal data from your customer order history because the database engine itself will reject the unauthorized request.

Implementation Tip

When using an ORM like Prisma or Sequelize, remember that the database driver honors the permissions of the database user provided in your connection string. Even if your ORM code defines 50 models, if the underlying database user lacks permissions for 48 of them, your application is inherently more secure.

Key Takeaway: Never use an administrative database user for your application; create restricted roles that limit access strictly to the tables required for authentication and session management.