Привилегии
Вы можете предоставлять и отменять привилегии для различных объектов базы данных в Oracle. Сначала мы рассмотрим, как предоставлять и отменять привилегии для таблиц, а затем, как предоставлять и отменять привилегии функциям и процедурам в Oracle.
Grant Privileges для таблиц
Вы можете предоставить пользователям различные привилегии к таблицам. Эти привилегии могут быть любой комбинацией SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALTER, INDEX, или другие.
Синтаксис
Синтаксис для предоставления привилегий для таблицы в Oracle/PLSQL:
privileges
Привилегии для назначения. Это может быть любое из следующих значений:
| Привилегии | Описание |
|---|---|
| SELECT | Возможность выполнения SELECT на таблице |
| INSERT | Возможность выполнения INSERT на таблице |
| UPDATE | Возможность выполнения UPDATE на таблице |
| DELETE | Возможность выполнения DELETE на таблице |
| REFERENCES | Возможность создавать CONSTRAINT, который ссылается на таблицу. |
| ALTER | Возможность выполнять оператор ALTER TABLE, чтобы изменить описание таблицы. |
| INDEX | Возможность создавать INDEX таблице с помощью оператора CREATE INDEX. |
| ALL | Все привилегии для таблицы |
object
наименование объекта базы данных, которому вы предоставляете привилегии. В случае предоставления привилегий таблице, это должно быть название таблицы.
user
Имя пользователя, которому будет предоставлена эта привилегия.
Пример
Рассмотрим некоторые примеры, предоставления привилегий для таблиц в Oracle.
Например, если вы хотите предоставить SELECT, INSERT, UPDATE и DELETE привилегии на таблицу с наименованием suppliers для user с именем trizor , то нужно выполнить следующие GRANT предложение:
How can I list ALL grants a user received?
I used the TOAD feature to compare schemas but it does not shows temptable grants etc. so there’s my question:
How can I list all grants on a Oracle DB?
7 Answers 7
If you want more than just direct table grants (e.g., grants via roles, system privileges such as select any table, etc.), here are some additional queries:
System privileges for a user:
Direct grants to tables/views:
Indirect grants to tables/views:
Assuming you want to list grants on all objects a particular user has received:
This will not return objects owned by the user. If you need those, use all_tab_privs view instead.
Sorry guys, but selecting from all_tab_privs_recd where grantee = ‘your user’ will not give any output except public grants and current user grants if you run the select from a different (let us say, SYS) user. As documentation says,
ALL_TAB_PRIVS_RECD describes the following types of grants:
So, if you’re a DBA and want to list all object grants for a particular (not SYS itself) user, you can’t use that system view.
In this case, you must perform a more complex query. Here is one taken (traced) from TOAD to select all object grants for a particular user:
This will list all object grants (including column grants) for your (specified) user. If you don’t want column level grants then delete all part of the select beginning with ‘union’ clause.
UPD: Studying the documentation I found another view that lists all grants in much simpler way:
Bear in mind that there’s no DBA_TAB_PRIVS_RECD view in Oracle.
How to Show All Oracle Database Privileges for a User
Retrieving all user privileges within Oracle can range from a simple task using a basic SQL query to an advanced script, depending primarily on how involved the roles and privileges are configured within the server.
In this brief tutorial, we’ll cover both the basic SQL query method as well as the advanced script method so you’ll have no issue regardless of the complexity of your setup.
Querying DBA/USER Privilege Views
A database administrator (DBA) for Oracle can simply execute a query to view the rows in DBA_SYS_PRIVS , DBA_TAB_PRIVS , and DBA_ROLE_PRIVS to retrieve information about user privileges related to the system , tables , and roles , respectively.
For example, a DBA wishing to view all system privileges granted to all users would issue the following query:
The DBA_SYS_PRIVS view contains three columns of data:
- GRANTEE is the name, role, or user that was assigned the privilege.
- PRIVILEGE is the privilege that is assigned.
- ADMIN_OPTION indicates if the granted privilege also includes the ADMIN option.
To determine which users have direct grant access to a table we’ll use the DBA_TAB_PRIVS view:
You can check the official documentation for more information about the columns returned from this query, but the critical columns are:
- GRANTEE is the name of the user with granted access.
- TABLE_NAME is the name of the object (table, index, sequence, etc).
- PRIVILEGE is the privilege assigned to the GRANTEE for the associated object.
Finally, querying the DBA_ROLE_PRIVS view has much of the same information but applicable to roles instead, where the GRANTED_ROLE column specifies the role in question:
Querying the Current User’s Privileges
If DBA access isn’t possible or necessary, it is also possible to slightly modify the above queries to view the privileges solely for the current user.
This is done by alternatively querying USER_ versions of the above DBA_ views. Thus, instead of looking at DBA_SYS_PRIVS we’d query USER_SYS_PRIVS , like so:
Since the USER_ privilege views are effectively the same as their DBA_ counterparts, but specific to the current user only, the type of returned data and column names are all identical to those when querying DBA_ views intead.
Advanced Script to Find All Privileges
While the above methods will work for basic system configurations, things start to become messy in Oracle when many roles exist which are in turn granting role privileges to other roles, and so on down the rabbit hole. Since the DBA_ and USER_ privilege views only display GRANTEES with directly assigned access, often privileges that are inhereted through other roles will not be readily shown.
To resolve this, it is advisable to use an advanced script such as the trusted work of Pete Finnigan and his find_all_privs.sql script. You may also opt for a modified version by David Arthur, find_all_privs2.sql .
In either case, the purpose of these scripts is to allow you to recursively locate all privileges granted to a particular user. When the script locates a role for the user, it recursively searches for other roles and privileges granted to that role, repeating the process all the way down the chain. The results of the script can be output to the screen or to a file as desired.
Управление доступом к базе данных Oracle:
Полномочия – это право на выполнение конкретного типа SQL-оператора или на доступ к объекту базы данных, принадлежащему другому пользователю. В базе данных Oracle необходимо явно предоставить пользователю полномочия для выполнения любых действий, включая подключение к базе данных или выборку, изменение и обновление данных в любой таблице, кроме собственной.
Существуют два основных типа полномочий Oracle: системные полномочия и объектные полномочия. Для предоставления пользователям как системных, так и объектынх полномочий служит оператор GRANT.
Системные полномочия:
Системные полномочия позволяют пользователю выполнить конкретное действие в базе данных либо действие с любым объектом схемы, конкретного типа. Хороший пример первого типа системных полномочий – полномочия, которые позволяют подключаться к базе данных, носящие название полномочий CONNECT. Другими полномочиями этого типа являются полномоичия CREATE TABLESPACE, CREATE USER, DROP USER и ALTER USER.
Второй класс системных полномоичий предоставляет пользователям право на выполнение операций, которыевлияют на объекты в любой схеме. Примерами этого типа системных полномочий служат ANALYZE ANY TABLE, GRANT ANY PRIVILEGE, INSERT ANY TABLE, DELETE ANY TABLE и т.п. Системные полномочия являются очень мощным средством и выдача их не тому пользователю может оказать разруши тельное влияние на базу данных.
Ниже перечислены некоторые наиболее часто используемые полномочия базы данных Oracle:
- ADVISOR
- ALTER DATABASE
- ALTER SYSTEM
- AUDIT SYSTEM
- CREATE DATABASE LINK
- CREATE TABLE
- CREATE ANY INDEX
- CREATE SESSION
- CREATE TABLESPACE
- CREATE USER
- DROP USER
- INSERT ANY TABLE
Пример:
Объектыные полномочия:
Объектыне полномочия – это полномочия по отношению к различным типам объектов базы данных. Объектыные полномочия дают пользователю возможность выполнять действия с конкретной таблицей, представлением, материализованным представлением, последовательностью, процедурой, функцией или пакетом. Следовательно, всем пользователям базы данных нужны объектные полномочия.
Для выдачи объектных полномочий можно использовать следующие SQL-операторы.