In a multitenant application, customers from different companies may share the same orders, invoices, or customer tables. The application usually adds WHERE TenantId = @TenantId to every query. That approach is fragile: one report, stored procedure, or maintenance query that forgets the filter can expose another tenant's data.
SQL Server Row-Level Security (RLS) moves row-access rules into the database layer. The database evaluates the policy whenever a protected table is queried or modified. In this article, we will isolate orders for two companies, pass the current tenant through SESSION_CONTEXT, and prevent users from inserting or updating rows for another tenant.
The Problem with Application-Only Filtering
Assume that dbo.Orders contains data for tenants 101 and 202. An API might execute the following query:
SELECT OrderId, TenantId, Amount, Status
FROM dbo.Orders
WHERE TenantId = @TenantId;The query is correct as long as every caller applies the same rule. In practice, several paths can bypass it:
- A reporting query may omit the tenant predicate.
- A maintenance procedure may receive the wrong tenant parameter.
- A new view may expose the base table without the expected filter.
- A user may update a row and change its
TenantIdto another company.
RLS reduces this class of error by enforcing the rule on the table itself. It does not replace authentication, authorization, or a trusted identity flow. If an application can freely set the tenant value in a shared database connection, the overall design is still unsafe.
Schema and Realistic Test Data
The following script is intended for an isolated test database. In production, introduce the objects through a controlled migration instead of dropping existing tables.
CREATE SCHEMA Security;
GO
CREATE TABLE dbo.Tenants
(
TenantId int NOT NULL
CONSTRAINT PK_Tenants PRIMARY KEY,
TenantName nvarchar(100) NOT NULL
);
GO
CREATE TABLE dbo.Orders
(
OrderId bigint IDENTITY(1,1) NOT NULL
CONSTRAINT PK_Orders PRIMARY KEY,
TenantId int NOT NULL,
CustomerId bigint NOT NULL,
OrderDate datetime2(0) NOT NULL
CONSTRAINT DF_Orders_OrderDate DEFAULT SYSUTCDATETIME(),
Amount decimal(19,4) NOT NULL,
Status varchar(20) NOT NULL,
CONSTRAINT FK_Orders_Tenants
FOREIGN KEY (TenantId) REFERENCES dbo.Tenants(TenantId)
);
GO
INSERT dbo.Tenants (TenantId, TenantName)
VALUES (101, N'Northwind Retail'),
(202, N'Contoso Services');
INSERT dbo.Orders (TenantId, CustomerId, Amount, Status)
VALUES (101, 9001, 1250.00, 'Open'),
(101, 9002, 275.50, 'Paid'),
(202, 7001, 8100.00, 'Open');
GO
CREATE INDEX IX_Orders_TenantId_OrderDate
ON dbo.Orders (TenantId, OrderDate)
INCLUDE (CustomerId, Amount, Status);
GOThe index begins with TenantId, which supports both the security predicate and common tenant-scoped order queries. On a large table, failing to index the predicate column can increase the cost of queries after RLS is enabled. Always validate the effect with representative data and execution plans.
Creating the RLS Predicate Function
The application will place the validated tenant identifier in the current SQL session. The predicate function compares the row's TenantId with that value.
CREATE FUNCTION Security.fn_TenantAccess
(
@TenantId int
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
(
SELECT 1 AS fn_access
WHERE @TenantId = TRY_CONVERT(int, SESSION_CONTEXT(N'tenant_id'))
);
GOAn inline table-valued function with SCHEMABINDING is the standard pattern for a SQL Server security predicate. If the session context value is missing or cannot be converted to an integer, the condition is false and no protected rows are returned.
Applying Filter and Block Predicates
Now create a security policy that protects both reads and writes:
CREATE SECURITY POLICY Security.OrderTenantPolicy
ADD FILTER PREDICATE Security.fn_TenantAccess(TenantId)
ON dbo.Orders,
ADD BLOCK PREDICATE Security.fn_TenantAccess(TenantId)
ON dbo.Orders AFTER INSERT,
ADD BLOCK PREDICATE Security.fn_TenantAccess(TenantId)
ON dbo.Orders AFTER UPDATE
WITH (STATE = ON);
GOThe filter predicate limits the rows visible to the current tenant. It also prevents operations against rows that are not visible. However, a filter alone is not the complete answer for inserts: an application might attempt to create a row with another tenant's identifier. The AFTER INSERT and AFTER UPDATE block predicates reject those writes.
For example, a tenant 101 session cannot insert a row with TenantId = 202. It also cannot change an existing tenant 101 order so that it belongs to tenant 202.
Setting SESSION_CONTEXT
For testing, set the session to tenant 101:
EXEC sys.sp_set_session_context
@key = N'tenant_id',
@value = 101;
SELECT OrderId, TenantId, CustomerId, Amount, Status
FROM dbo.Orders
ORDER BY OrderId;The query should return only the two orders belonging to tenant 101. Change the session value to 202 and execute the same query again:
EXEC sys.sp_set_session_context
@key = N'tenant_id',
@value = 202;
SELECT OrderId, TenantId, CustomerId, Amount, Status
FROM dbo.Orders;Only the order for tenant 202 should be returned. In a production application, the value must not come directly from an untrusted request header or form field. The tenant claim should be validated on the server, and only then should the application set the SQL session context.
This is especially important when a middle tier uses one shared SQL login. A user who can connect directly to the database and call sp_set_session_context with an arbitrary tenant value may bypass the intended trust boundary. Restrict direct database access and grant the application account only the permissions it actually needs.
Testing Invalid Tenant Writes
Reading is only half of the test. Verify that cross-tenant writes are rejected:
EXEC sys.sp_set_session_context
@key = N'tenant_id',
@value = 101;
-- This should fail because of the block predicate.
INSERT dbo.Orders (TenantId, CustomerId, Amount, Status)
VALUES (202, 9999, 50.00, 'Open');
-- This should also fail because ownership is being changed.
UPDATE dbo.Orders
SET TenantId = 202
WHERE OrderId = 1;Both operations should fail with a security policy error. The application should record the event as an authorization or workflow failure rather than returning a vague success response. Avoid writing access tokens or unnecessary sensitive data to the application log.
Connection Pooling and Context Leakage
SESSION_CONTEXT belongs to the SQL session. With ADO.NET connection pooling, calling Close often returns the physical connection to the pool instead of destroying it. Every time a connection is leased, the application must set the correct tenant context before executing tenant-sensitive work. It must never rely on the value left by the previous request.
The @read_only = 1 option makes a context key immutable for the lifetime of the connection. That can be useful when the connection is dedicated to one identity, but it requires care with pooled connections that may later serve another identity. Do not enable read-only context values unless your connection-lifecycle design guarantees that the physical connection cannot be reused across identities.
Operational Checklist
- Grant the application only the required table, view, and procedure permissions; do not use
db_ownerfor routine application access. - Index the columns used by the security predicate and measure real workload performance.
- Set the session context every time a pooled connection is acquired for tenant work.
- Automate tests for SELECT, INSERT, UPDATE, and DELETE behavior.
- Define separately what administrators, ETL jobs, reporting users, and change-data processes are allowed to see.
- If temporal tables are involved, remember that a policy on the current table is not automatically copied to the history table. Protect the history table separately when required.
- Treat disabling a security policy as a controlled migration or incident procedure, not as a routine troubleshooting shortcut.
Conclusion
SQL Server Row-Level Security creates a centralized database boundary instead of relying on every application query to remember a tenant filter. A dependable implementation combines three elements: a schemabound predicate function, a trustworthy process for populating SESSION_CONTEXT, and block predicates that reject invalid tenant ownership changes.
RLS still requires operational validation. Test connection pooling, administrator access, ETL behavior, indexing, historical tables, and invalid writes with production-like data volumes. Once these details are addressed, RLS provides a strong and maintainable defense against forgotten WHERE clauses in multitenant SQL Server systems.
Sources
- https://learn.microsoft.com/en-us/sql/relational-databases/security/row-level-security?view=sql-server-ver17
- https://learn.microsoft.com/en-us/azure/data-api-builder/azure-sql-session-context-rls
- https://learn.microsoft.com/en-us/sql/relational-databases/security/secure-sql-server?view=sql-server-ver17
- https://www.tugrulbostan.com/blog/kesintisiz-veritabani-migration-stratejisi
0 Comments