Limit PostgreSQL user access using schema and views

To limit PostgreSQL access to specific tables and columns you can use schema and selective GRANT statements.

If you only need to limit access to certain tables the instructions found here should work nicely.

However, if you need to limit access to specific columns you may need to use a combination of schemas and views to restrict access.  You may also to do this if your database has over 1000 tables and you are attempting to connect to Chartio.

1.  Connect to your PostgreSQL database using psql or pgadmin.  Run the following to return a list of tables in your database.

sudo -u postgres psql
\c databasename;

2.  To create a schema specific to Chartio's read only user run the following.

CREATE SCHEMA chartio_read_only;
CREATE ROLE chartio_schema_user LOGIN PASSWORD 'secure_password';
GRANT CONNECT ON DATABASE databasename TO chartio_schema_user;
GRANT USAGE ON SCHEMA chartio_read_only TO chartio_schema_user;

3.  Now let's take a look at the database relations using the \d command.

\d

 Schema | Name          | Type  | Owner
----------+-------------------------+----------+--------------
 public | Accounts      | table | postgres
 public | Visitors      | table | postgres
 public | Users         | table | postgres
 public | Subscriptions | table | postgres

3.  Your Accounts table has sensitive information in it, and you want Chartio to access only the Account_ID and Date_Created columns.  You can run the following to add a view to the chartio_read_only schema and grant access to that view to the chartio_schema_user.

CREATE VIEW chartio_read_only."Accounts" AS SELECT Account_ID, Date_Created FROM Accounts;
GRANT SELECT ON chartio_read_only."Accounts" TO chartio_schema_user;

4.  Now let's grant permissions to select all data from the Visitors table.

CREATE VIEW chartio_read_only."Visitors" AS SELECT * FROM Visitors;
GRANT SELECT ON chartio_read_only."Visitors" TO chartio_schema_user;

5.  Now if you connect the chartio_schema_user to your database it will only be able to access the two limited views you have granted to the schema.

For more information consult the PostgreSQL documentation.