Oracle посмотреть роли пользователя
Я уверен, что об этом уже спрашивали, но я не могу найти соответствующие детали для следующего.
Существует ли какая-то предварительно созданная таблица, которая может выполнять следующие действия (я использовал dba_tab_privs, но она ограничена и не отвечает всем моим потребностям), если нет, у кого-нибудь есть вопросы для ответа на следующие вопросы?
- Список всех пользователей, которым была назначена определенная роль?
- Перечислите все роли, данные пользователю?
- Список всех привилегий, предоставленных пользователю?
- Список таблиц, к которым определенная роль дает доступ SELECT?
- Список всех таблиц, из которых пользователь может выбрать?
- Перечислите всех пользователей, которые могут ВЫБРАТЬ на определенной таблице (либо с помощью соответствующей роли, либо с помощью прямого гранта (то есть, гранта выбора на atable to joe))? Результат этого запроса также должен показать, через какую роль пользователь имеет этот доступ или был ли это прямой грант.
Список всех пользователей, которым была назначена определенная роль
Перечислите все роли, данные пользователю
Перечислите все привилегии, данные пользователю
Список таблиц, к которым определенная роль дает доступ SELECT?
Список всех таблиц, из которых пользователь может выбрать?
Перечислите всех пользователей, которые могут ВЫБРАТЬ на определенной таблице (либо с помощью соответствующей роли, либо с помощью прямого гранта (то есть, гранта выбора на atable to joe))? Результат этого запроса также должен показать, через какую роль пользователь имеет этот доступ или был ли это прямой грант.
Есть много способов получить информацию, которую вы хотите использовать:
присутствует в оракуле.
Вы можете просто запросить представления и получить подробную информацию: Например:
выберите * из DBA_COL_PRIVS;
выберите * из ALL_COL_PRIVS;
выберите * из USER_COL_PRIVS;
Это говорит вам:
Представление DBA описывает все разрешения объектов столбцов в базе данных. Представление ALL описывает все разрешения объекта столбца, для которых текущий пользователь или PUBLIC является владельцем объекта, лицом, предоставляющим право или получателем. Представление USER описывает разрешения объекта столбца, для которых текущий пользователь является владельцем объекта, лицом, предоставившим право или получателем.
Для получения дополнительной информации, проверьте это
Надеюсь это поможет.
Похоже, это не отвечает на вопрос: как администратор БД может узнать, что может получить доступ к конкретному произвольному пользователю?
таким образом, Apex имеет "рабочие области", которые позволяют создавать пользователей трех типов - все из которых являются внутренними для организации по своей природе. Кроме того, кажется, что разработчик отдельного сайта на Apex не может иметь "пользователей" только для своего сайта.
Я что-то пропустила?
Мне нужно иметь возможность иметь внешних (бизнес) пользователей, чтобы иметь возможность получить доступ только к некоторым функциям сайта, например, бухгалтерский учет может видеть только страницы A и B, в то время как руководители могут видеть A, B и C.
Мне нужно иметь возможность иметь несколько групп людей с разными степенями доступа.
Это можно сделать только путем создания рабочих групп? Или это можно сделать внутри только на моем сайте?
хотя APEX имеет встроенную концепцию управления пользователями под названием "группы", я должен признаться, что никогда не использовал ее, и быстрый просмотр документации не дает мне понять, как вы используете их для управления доступом (но см. Тома здесь).
вероятно, вам потребуется создать таблицы пользователей/ролей в базе данных и использовать их вместе со схемами авторизации APEX для управления доступом к страницам. Единая схема авторизации типа " PL / SQL Функция, возвращающая логическое значение" может быть создан с помощью функции:
затем вы реализуете пакет, чтобы найти права пользователя и решить, возвращать ли TRUE или FALSE для приложения и идентификатора страницы.
в качестве альтернативы вы можете просто выполнить SQL для проверки доступа непосредственно в схеме авторизации:
(NB " user_roles "и" role_pages " - это имена, которые я придумал, чтобы представить код таблицы)
Я просто хочу расширить Тони, что само по себе является правильным. Я просто хочу показать вам другой способ, который, я думаю, будет проще для новичка и опустит создание таблиц.
Если приложение использует Apex в качестве схемы проверки подлинности, то управление пользователями осуществляется посредством администрирования самой рабочей области. Можно создавать, редактировать и удалять пользователей, но можно также определять группы и связывать пользователей с группами. Это возможно для вас, чтобы создать несколько" конечных пользователей "типа пользователей и определяют пару групп, таких как"руководители".
После создания группы перейдите к пользователю, которому вы хотите назначить эту группу, и добавьте группу в группы этого пользователя
Как только вы это настроите, вам все еще нужны схемы авторизации. Факт остается фактом, вам нужны некоторые знания pl/sql здесь, но можно свести кодирование к минимуму, благодаря некоторым удобным api-работа. The current_user_in_group делает то, что он говорит: он проверяет для текущего пользователя, если он сказал, что группа. С некоторым расширением, используя некоторые простые IF-структуры, вы можете немного увеличить его!
Не то, чтобы я полностью рекомендовал этот метод, я нахожу его немного утомительным, и вам нужен кто-то, чтобы войти в APEX, чтобы фактически поддерживать пользователей и их группы, но вполне может быть, что это приемлемо в вашей среде. Вы можете использовать его, чтобы начать с однако. Вы можете очень легко переключить схемы аутентификации, и с изменением схем авторизации, чтобы они соответствовали новой схеме аутентификации, вы можете легко и быстро настроить это позже. Это зависит от ваших приоритетов и целей курса.
авторизация-это процесс определения того, разрешено ли аутентифицированному / идентифицированному лицу получить доступ к ресурсу или выполнить операцию. Он основан на наборе привилегий или ролей, назначенных пользователю. Например, в базе данных Oracle администратор имеет право планировать задания, а пользователь-нет. Чем авторизация отличается от аутентификации? Часто аутентификация и авторизация работают вместе. Другими словами, авторизация следует за аутентификацией. Идентификация определяет, кто вы? Авторизация определяет, что вам разрешено делать?
вы должны рассматривать схему как учетную запись пользователя и коллекцию всех объектов в ней как схема для всех намерений и целей.
SCOTT-это схема, которая включает таблицы EMP, DEPT и BONUS с различными грантами и другая вещь.
SYS-это схема, которая включает тонны таблиц,представлений, грантов и т. д.
технически -- схема-это набор метаданные (словарь данных), используемые базой данных, обычно генерируется с помощью DDL. Схема определяет атрибуты базы данных, такие как таблицы, столбцы и свойства. Схема базы данных-это описание данных в база данных.
Я считаю, что проблема в том, что Oracle использует термин - схемы немного отличается от того, что это обычно означает.
- схема Oracle (как объясняется в ответе Nebakanezer): в основном набор всех таблиц и других объектов, принадлежащих учетной записи пользователя, поэтому примерно эквивалентен учетной записи пользователя
- схемы в целом: совокупность всех таблиц, хранимые процедуры и т. д. которые составляют базу данных для данной системы / приложения (как в "разработчики должны обсудить с данных о схеме для нашего нового приложения.")
схема в смысле 2. похож, но не совпадает схема в смысле 1. Е. Г. для приложения, которое использует несколько учетных записей БД, схему в смысле 2 может состоять из нескольких схем в Oracle :-).
плюс - схемы может также означать кучу других, довольно несвязанных вещей в других контекстах (например, в математике).
Oracle должен был просто использовать термин "userarea" или "accountobjects", вместо overloadin "схемы".
- схема является коллекцией объектов базы данных, включая логические структуры, такие как таблицы, представления, последовательности, хранимые процедуры, синонимы, индексы, кластеры и связи баз данных.
- пользователь владеет схемой.
- пользователь и схема имеют одинаковое имя.
- команда CREATE USER создает пользователя. Она также автоматически создает схему для этого пользователя.
- команда CREATE SCHEMA выполняет не создавайте "схему", как это подразумевается, она просто позволяет создавать несколько таблиц и представлений и выполнять несколько грантов в вашей собственной схеме в одной транзакции.
- для всех намерений и целей вы можете рассмотреть пользователю схемой и схемой пользователя.
кроме того, пользователь может получить доступ к объектам в схемах, отличных от их собственных, если у них есть разрешение на это.
подумайте о пользователе, как вы обычно делаете (имя пользователя/пароль с доступом для входа и доступа к некоторым объектам в системе), и схема как версия базы данных домашнего каталога пользователя. Пользователь " foo "обычно создает вещи по схеме" foo", например, если пользователь" foo "создает или ссылается на таблицу" bar", то Oracle предположит, что пользователь означает " foo.бар."
этот ответ не определяет разницу между владельцем и схемой, но я думаю, что он добавляет к обсуждению.
в моем маленьком мире мышления:
я боролся с идеей, что я создаю N количество пользователей, где я хочу, чтобы каждый из этих пользователей "потреблял" (aka, use) одну схему.
Тим на oracle-base.com показывает, как это сделать (есть N количество пользователей, и каждый из этих пользователей будет "перенаправлен" на один схема.
у него есть второй подход "синоним" (не указан здесь). Я только цитирую версию CURRENT_SCHEMA (один из его подходов) здесь:
CURRENT_SCHEMA подход
этот метод использует CURRENT_SCHEMA атрибут сеанса автоматически укажите пользователям приложения правильную схему.
во-первых, мы создаем владельца схемы и пользователя приложения.
обратите внимание, что приложение пользователя может подключаться, но не имеет квоты или привилегии табличного пространства для создания объектов.
затем мы создаем некоторые роли, чтобы разрешить доступ только для чтения и записи.
мы хотим предоставить нашему пользователю приложения доступ для чтения и записи в схему объекты, поэтому мы предоставляем соответствующую роль.
мы должны убедиться, что пользователь приложения имеет свою схему по умолчанию указывая на владельца схемы, мы создаем триггер AFTER LOGON для сделать это для нас.
теперь мы готовы создать объект в владельца схемы.
обратите внимание, как привилегии предоставляются соответствующим ролям. Без эти объекты не будут видны пользователю приложения. Мы сейчас иметь действующего владельца схемы и пользователя приложения.
этот метод идеально подходит, когда пользователь приложения-это просто альтернативная точка входа в основную схему, не требующая объектов свой собственный.
Это очень просто.
пользователю может быть предоставлен доступ к объектам схемы, принадлежащие разным пользователям.
Many tasks, with many interwoven considerations, are involved in administering user privileges, roles, and profiles. These necessary operations and principles are discussed in the following sections:
Managing Oracle Users
Each Oracle database has a list of valid database users. To access a database, a user must run a database application and connect to the database instance using a valid user name defined in the database. This section explains how to manage users for a database, and contains the following topics:
Oracle Database SQL Reference for more information about SQL statements used for managing users
Системные полномочия:
Системные полномочия позволяют пользователю выполнить конкретное действие в базе данных либо действие с любым объектом схемы, конкретного типа. Хороший пример первого типа системных полномочий – полномочия, которые позволяют подключаться к базе данных, носящие название полномочий 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
Пример:
Creating Users
You create a database user with the CREATE USER statement. To create a user, you must have the CREATE USER system privilege. Because it is a powerful privilege, a DBA or security administrator is normally the only user who has the CREATE USER system privilege.
Example 11-1 creates a user and specifies the user password, default tablespace, temporary tablespace where temporary segments are created, tablespace quotas, and profile.
Example 11-1 Create a User and Grant the Create Session System Privilege
A newly created user cannot connect to the database until granted the CREATE SESSION system privilege.
As administrator, you should create your own roles and assign only those privileges that are needed. For example, many users formerly granted the CONNECT privilege did not need the additional privileges CONNECT used to provide. Instead, only CREATE SESSION was actually needed, and in fact that is the only privilege CONNECT presently retains.
Creating its own roles gives an organization detailed control of the privileges it assigns, and protects it in case Oracle changes the roles that it defines. For example, both CONNECT and RESOURCE roles will be deprecated in future Oracle versions.
This section refers to the preceding example as it discusses the following aspects of creating a user:
Granting System Privileges and Roles on page 25-11
Specifying a Name
Within each database, a user name must be unique with respect to other user names and roles. A user and role cannot have the same name. Furthermore, each user has an associated schema. Within a schema, each schema object must have a unique name.
Setting Up User Authentication
In Example 11-1, the new user is to be authenticated using the database. In this case, the connecting user must supply the correct password to the database to connect successfully.
Selecting and specifying the method of user authentication is discussed in "User Authentication Methods".
Assigning a Default Tablespace
Each user should have a default tablespace. When a user creates a schema object and specifies no tablespace to contain it, Oracle Database stores the object in the default user tablespace.
The default setting for the default tablespaces of all users is the SYSTEM tablespace. If a user does not create objects, and has no privileges to do so, then this default setting is fine. However, if a user is likely to create any type of object, then you should specifically assign the user a default tablespace. Using a tablespace other than SYSTEM reduces contention between data dictionary objects and user objects for the same data files. In general, it is not advisable for user data to be stored in the SYSTEM tablespace.
You can create a permanent default tablespace other than SYSTEM at the time of database creation, to be used as the database default for permanent objects. By separating the user data from the system data, you reduce the likelihood of problems with the SYSTEM tablespace, which can in some circumstances cause the entire database to become nonfunctional. This default permanent tablespace is not used by system users, that is, SYS , SYSTEM , and OUTLN , whose default permanent tablespace remains SYSTEM . A tablespace designated as the default permanent tablespace cannot be dropped. To accomplish this goal, another tablespace must first be designated as the default permanent tablespace. It is possible to ALTER the default permanent tablespace to another tablespace, affecting all users or objects created after the ALTER DDL commits.
You can also set a user default tablespace during user creation, and change it later with the ALTER USER statement. Changing the user default tablespace affects only objects created after the setting is changed.
When you specify the default tablespace for a user, also specify a quota on that tablespace.
In Example 11-1, the default tablespace for user jward is data_ts , and his quota on that tablespace is 500K .
Assigning Tablespace Quotas
You can assign each user a tablespace quota for any tablespace (except a temporary tablespace). Assigning a quota does the following things:
Users with privileges to create certain types of objects can create those objects in the specified tablespace.
Oracle Database limits the amount of space that can be allocated for storage of a user's objects within the specified tablespace to the amount of the quota.
By default, a user has no quota on any tablespace in the database. If the user has the privilege to create a schema object, then you must assign a quota to allow the user to create objects. Minimally, assign users a quota for the default tablespace, and additional quotas for other tablespaces in which they can create objects.
You can assign a user either individual quotas for a specific amount of disk space in each tablespace or an unlimited amount of disk space in all tablespaces. Specific quotas prevent a user's objects from consuming too much space in the database.
You can assign quotas to a user tablespace when you create the user, or add or change quotas later. If a new quota is less than the old one, then the following conditions hold true:
If a user has already exceeded a new tablespace quota, then the user's objects in the tablespace cannot be allocated more space until the combined space of these objects falls below the new quota.
If a user has not exceeded a new tablespace quota, or if the space used by the user's objects in the tablespace falls under a new tablespace quota, then the user's objects can be allocated space up to the new quota.
Revoking User Ability to Create Objects in a Tablespace
You can revoke the ability of a user to create objects in a tablespace by changing the current quota of the user to zero. After a quota of zero is assigned, the user's objects in the tablespace remain, but new objects cannot be created and existing objects cannot be allocated any new space.
UNLIMITED TABLESPACE System Privilege
To permit a user to use an unlimited amount of any tablespace in the database, grant the user the UNLIMITED TABLESPACE system privilege. This overrides all explicit tablespace quotas for the user. If you later revoke the privilege, then explicit quotas again take effect. You can grant this privilege only to users, not to roles.
Before granting the UNLIMITED TABLESPACE system privilege, you must consider the consequences of doing so.
You can grant a user unlimited access to all tablespaces of a database with one statement.
The privilege overrides all explicit tablespace quotas for the user.
You cannot selectively revoke tablespace access from a user with the UNLIMITED TABLESPACE privilege. You can grant selective or restricted access only after revoking the privilege.
Assigning a Temporary Tablespace
Each user also should be assigned a temporary tablespace . When a user executes a SQL statement that requires a temporary segment, Oracle stores the segment in the user's temporary tablespace. These temporary segments are created by the system when doing sorts or joins and are owned by SYS , which has resource privileges in all tablespaces.
In the previous CREATE USER statement, the temporary tablespace of jward is temp_ts , a tablespace created explicitly to contain only temporary segments. Such a tablespace is created using the CREATE TEMPORARY TABLESPACE statement.
If the temporary tablespace of a user is not explicitly set, then the user is assigned the default temporary tablespace that was specified at database creation, or by an ALTER DATABASE statement at a later time. If there is no default temporary tablespace explicitly assigned, then the default is the SYSTEM tablespace or another permanent default established by the system administrator. It is not advisable for user data to be stored in the SYSTEM tablespace. Also, assigning a tablespace to be used specifically as a temporary tablespace eliminates file contention among temporary segments and other types of segments.
If your SYSTEM tablespace is locally managed, then users must be assigned a specific default (locally managed) temporary tablespace. They may not be allowed to default to using the SYSTEM tablespace because temporary objects cannot be placed in permanent locally managed tablespaces.
You can set the temporary tablespace for a user at user creation, and change it later using the ALTER USER statement. Do not set a quota for temporary tablespaces. You can also establish tablespace groups instead of assigning individual temporary tablespaces.
Multiple Temporary Tablespaces: Using Tablespace Groups
Specifying a Profile
You also specify a profile when you create a user. A profile is a set of limits on database resources and password access to the database. If no profile is specified, then the user is assigned a default profile.
Setting Default Roles
You cannot set default roles for a user in the CREATE USER statement. When you first create a user, the default role setting for the user is ALL , which causes all roles subsequently granted to the user to be default roles. Use the ALTER USER statement to change the default roles for the user.
Altering Users
Users can change their own passwords. However, to change any other option of a user security domain, you must have the ALTER USER system privilege. Security administrators are typically the only users that have this system privilege, as it allows a modification of any user security domain. This privilege includes the ability to set tablespace quotas for a user on any tablespace in the database, even if the user performing the modification does not have a quota for a specified tablespace.
You can alter user security settings with the ALTER USER statement. Changing user security settings affects the future user sessions, not current sessions.
The following statement alters the security settings for the user, avyrros :
The ALTER USER statement here changes the security settings for the user avyrros as follows:
Authentication is changed to use the operating system account of the user avyrros .
The default and temporary tablespaces are explicitly set for user avyrros .
avyrros is given a 100M quota for the data_ts tablespace.
The quota on the test_ts is revoked for the user avyrros .
avyrros is assigned the clerk profile.
Changing User Authentication Mechanism
Most non-DBA users can still change their own passwords with the ALTER USER statement, as follows:
No special privileges (other than those to connect to the database) are required for a user to change passwords. Users should be encouraged to change their passwords frequently.
Users must have the ALTER USER privilege to switch between methods of authentication. Usually, only an administrator has this privilege.
"User Authentication Methods" for information about authentication methods that are available for Oracle Database users
Changing User Default Roles
A default role is one that is automatically enabled for a user when the user creates a session. You can assign a user zero or more default roles.
Viewing Information About Database Users and Profiles
The wide variety of options that are available for viewing such information are discussed in the following subsections:
Полномочия – это право на выполнение конкретного типа SQL-оператора или на доступ к объекту базы данных, принадлежащему другому пользователю. В базе данных Oracle необходимо явно предоставить пользователю полномочия для выполнения любых действий, включая подключение к базе данных или выборку, изменение и обновление данных в любой таблице, кроме собственной.
Существуют два основных типа полномочий Oracle: системные полномочия и объектные полномочия. Для предоставления пользователям как системных, так и объектынх полномочий служит оператор GRANT.
Объектыные полномочия:
Объектыне полномочия – это полномочия по отношению к различным типам объектов базы данных. Объектыные полномочия дают пользователю возможность выполнять действия с конкретной таблицей, представлением, материализованным представлением, последовательностью, процедурой, функцией или пакетом. Следовательно, всем пользователям базы данных нужны объектные полномочия.
Для выдачи объектных полномочий можно использовать следующие SQL-операторы.
Dropping Users
When a user is dropped, the user and associated schema are removed from the data dictionary and all schema objects contained in the user schema, if any, are immediately dropped .
If a user schema and associated objects must remain but the user must be denied access to the database, then revoke the CREATE SESSION privilege from the user.
Do not attempt to drop the SYS or SYSTEM user. Doing so will corrupt your database.
A user that is currently connected to a database cannot be dropped. To drop a connected user, you must first terminate the user sessions using the SQL statement ALTER SYSTEM with the KILL SESSION clause.
You can drop a user from a database using the DROP USER statement. To drop a user and all the user schema objects (if any), you must have the DROP USER system privilege. Because the DROP USER system privilege is powerful, a security administrator is typically the only type of user that has this privilege.
If the user's schema contains any dependent schema objects, then use the CASCADE option to drop the user and all associated objects and foreign keys that depend on the tables of the user successfully. If you do not specify CASCADE and the user schema contains dependent objects, then an error message is returned and the user is not dropped. Before dropping a user whose schema contains objects, thoroughly investigate which objects the user's schema contains and the implications of dropping them. Pay attention to any unknown cascading effects. For example, if you intend to drop a user who owns a table, then check whether any views or procedures depend on that particular table.
The following statement drops the user, jones and all associated objects and foreign keys that depend on the tables owned by jones .
Oracle Database Administrator's Guide for more information about terminating sessions
Читайте также: