Sql-server – Simple question about schema (is this supposed to happen?)

schemasql serversql-server-2012

I've created a simple database, a table, a schema, and a table with that schema ( so, 2 tables ).

--sysadmin
create database dba_schema
go

use dba_schema 
go

create table tabela1 ( id int ) 
go

--LOGIN---------------------------------------------  
USE [master]
GO
CREATE LOGIN [schema_user] WITH PASSWORD=N'schema_user', 
DEFAULT_DATABASE=[dba_schema], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
USE [dba_schema]
GO
CREATE USER [schema_user] FOR LOGIN [schema_user]
GO
USE [dba_schema]
GO
ALTER USER [schema_user] WITH DEFAULT_SCHEMA=[dbo]
GO

( Manually I gave read, write and DLL permissions )
------------------------------------------------

create schema schema1
go

create table schema1.tabela1 ( id int ) 
go

Then I connected with the user schema_user ( that has now only read, write, and ddl permission ).

But, even not giving permission to that schema, I could select both tables ( dbo schema, and the schema I've created )

select * from dbo.tabela1

select * from schema1.tabela1

Is this supposed to happen? I thought that, when we create a schema, we should GRANT permission to that schema, for a user to select from it, but as I see, after creating a schema, we should DENY permission on it, for user not to select. Is this approach right? Its default schema is DBO.

Best Answer

I would confirm that you are connecting using the correct login, and that you have not incorrectly assigned some other permission.

I executed the script that you provided above, and then used execute as to test the select permissions and received SELECT permission denied errors for both (as I would expect).

Adjusted comments slightly, but the following I received what I expected (SQL Server 2012)

/* Create new database */
CREATE database dba_schema
GO

use dba_schema 
GO

/* Create new table in dbo schema */
CREATE TABLE dbo.tabela1 ( id int ) 
GO

/* Add new login */  
USE [master]
GO
CREATE LOGIN [schema_user] WITH PASSWORD=N'schema_user', 
DEFAULT_DATABASE=[dba_schema], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO

/* Add new user */
USE [dba_schema]
GO
CREATE USER [schema_user] FOR LOGIN [schema_user]
GO

/* Set default schema for user */
USE [dba_schema]
GO
ALTER USER [schema_user] WITH DEFAULT_SCHEMA=[dbo]
GO

/* Create new schema */
CREATE SCHEMA schema1
GO

/* Add new table to new schema */
CREATE TABLE schema1.tabela1 ( id int ) 
GO

/* Impersonate the new login of schema_user and query the tables */
EXECUTE AS LOGIN = 'schema_user';
/* Confirm we've impersonated correctly */
SELECT SUSER_NAME();
/* Run the selects */
SELECT * FROM dbo.tabela1;
SELECT * FROM schema1.tabela1;
REVERT;