Advertisement
Guest User

Untitled

a guest
Sep 8th, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. USE TestDB
  2. GO
  3.  
  4. -- Test Table
  5. CREATE TABLE dbo.Test
  6. (
  7. ID INT IDENTITY(1,1)
  8. , VALUE NVARCHAR(50)
  9. )
  10. GO
  11.  
  12. -- Test Data
  13. INSERT INTO dbo.Test (VALUE)
  14. VALUES
  15. ('blah'), ('blah'), ('blah'), ('yackity'), ('schmackity')
  16. GO
  17.  
  18. -- Create Special Schema that will "Own" all the Views
  19. CREATE SCHEMA viewSchema AUTHORIZATION dbo
  20. GO
  21.  
  22. -- Create a View on top of the Test Table
  23. CREATE VIEW viewSchema.testView
  24. AS
  25. SELECT ID
  26. , VALUE
  27. FROM dbo.Test
  28. GO
  29.  
  30. -- Create a new DB Role
  31. CREATE ROLE db_viewreader
  32. GO
  33.  
  34. -- Grant SELECT to all objects in the viewSchema schema to the new DB role
  35. GRANT SELECT ON SCHEMA::viewSchema TO db_viewreader
  36. GO
  37.  
  38.  
  39. -- Create a new Test User
  40. USE master
  41. GO
  42.  
  43. CREATE LOGIN testuser WITH PASSWORD=N'test', DEFAULT_DATABASE=TestDB, CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
  44. GO
  45.  
  46. USE TestDB
  47. GO
  48. CREATE USER testuser FOR LOGIN testuser
  49. GO
  50. ALTER ROLE db_viewreader ADD MEMBER testuser
  51. GO
  52.  
  53.  
  54. -- Execute the following block of code as the testuser account
  55. EXECUTE AS USER = 'testuser'
  56.  
  57.  
  58. SELECT *
  59. FROM dbo.Test
  60.  
  61. SELECT *
  62. FROM viewSchema.testView
  63.  
  64.  
  65. -- Revert my security context back to sa
  66. REVERT;
  67.  
  68. -- Cleanup
  69. ALTER ROLE [db_viewreader] DROP MEMBER [testuser]
  70. DROP ROLE db_viewreader
  71. DROP VIEW viewSchema.testView
  72. DROP SCHEMA viewSchema
  73. DROP TABLE dbo.Test
  74. DROP USER [testuser]
  75. GO
  76. USE [master]
  77. GO
  78. DROP LOGIN testuser
  79. GO
  80.  
  81. (5 row(s) affected)
  82. Msg 229, Level 14, State 5, Line 58
  83. The SELECT permission was denied on the object 'Test', database 'TestDB', schema 'dbo'.
  84.  
  85. (5 row(s) affected)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement