SQL Server Row Level Security by Example
SQL Server Row Level Security by Example
https://www.sqlnethub.com/blog/sql-server-2016-row-level-security/
SQL Server Row Level Security (RLS) is one of the top new features shipped in SQL Server 2016. With RLS, you can control access
to rows in a table based on the characteristics of the user executing a query.
The access restriction logic is located in the database tier and access restrictions are always applied, thus they cannot be skipped.
• Below I will showcase SQL Server Row-Level Security with the use of a simple scenario.
• This example features a fictitious school’s database and more specifically a table containing the school’s student records.
Each student is assigned an advisor.
• By using Row-Level Security, it is possible for each advisor to see only the records of his students.
• In the same scenario, only the school principal can view all student records.
--
-- Row Level Security Example
--
USE master;
GO
Now let’s grant SELECT access to all users which are the three advisors and the principal:
Now it’s time to create the Security policy. First we have to create the schema:
Then, we need to create the function that will be used for checking the executing user:
Finally we create and enable the security policy which uses the schema and the function created above:
If we execute the above query as the user ‘Advisor1‘ we can only see the student records that have ‘Advisor1’ as their advisor:
If we execute the above query as the user ‘Advisor2‘ we can only see the student records that have ‘Advisor2’ as their advisor:
If we execute the above query as the user ‘Advisor3‘ we can only see the student records that have ‘Advisor3’ as their advisor:
If we execute the above query as the user ‘Principal‘ we can see all student records:
If we disable the policy, then we return to the original state where all the records are retrieved from the tblStudents table within
the context of any user that was granted the SELECT permission on the table:
From the above example you can see that it’s quite easy to control access to your data at the most granular level in the database,
that is the record level, by using Row-Level Security in SQL Server 2016 or later.