Sei sulla pagina 1di 44

Using Privileges and Roles

Learning Objectives

After completing this topic, you should be able to

recognize how roles and privileges can be used

recognize how to use secure application roles

1. Authorizing a role
Authorization is the process that determines the privileges that the user is allowed to
exercise. In Oracle Database, authorization is determined by the grant of system and
object privileges. A named set of grants is a role, and it may be granted as a unit.

Supplement
Selecting the link title opens the resource in a new browser window.

Learning Aid
Access the learning aid Style Considerations for more information on the style
considerations for the Oracle 11g Database used in this course.
A privilege is a right to execute a particular type of SQL statement or to access another
user's object. Oracle Database allows very fine-grained control over what users can or
cannot do within the database. Privileges are divided into two categories:
system privileges and
Each system privilege allows a user to perform a particular database operation or class of
database operations (for example, the privilege to create tablespaces is a system
privilege). System privileges can be granted by the administrator or by someone who
explicitly gives permission to administer the privilege. There are over 150 distinct system
privileges.
object privileges
Object privileges allow a user to perform a particular action on a specific object, such as a
table, view, sequence, procedure, function, or package. Without specific permission, users
can access only their own objects. Object privileges can be granted by the owner of an
object, by the administrator, by someone with GRANT ANY PRIVILEGE, or by someone
who has been explicitly given permission to grant privileges on the object.

In most systems, it is too time consuming to grant necessary privileges to each user
individually, and there is too great a chance of error. Oracle Database provides for easy
and controlled privilege management through roles. Roles are named groups of related
privileges that are granted to users or to other roles.

Graphic
In this example, users Girard and Vance are assigned to the HR_CLERK role, and
user Neena is assigned to the HR_CLERK and HR_MGR roles. The HR_CLERK
role consists of Select employees and Update employees privileges and the
HR_MGR role consists of Delete employees and Insert employees privileges.
Roles are designed to ease the administration of privileges in the database and therefore,
they improve security. There are six characteristics for a role:

Privileges are granted to and revoked from roles as though the role were a user.
Roles can be granted to and revoked from users or other roles as though they were system
privileges. An exception is that you cannot grant the IDENTIFIED GLOBALLY role to anything.

A role can consist of both system and object privileges.

A role can be enabled or disabled for each user who is granted the role.

A role can require a password to be enabled.

Roles are not owned by anyone, and they are not in any schema.
In this example, the HR_CLERK role is granted the SELECT and UPDATE privileges on the
EMPLOYEES table. The HR_MGR role is granted the DELETE and INSERT privileges on the
EMPLOYEES table and the HR_CLERK role. The manager is granted the HR_MGR role and
can now select, delete, insert, and update the EMPLOYEES table.
Benefits of roles are
easier privilege management
Rather than granting the same set of privileges to several users, you can grant the
privileges to a role, and then grant that role to each user.
dynamic privilege management
Dynamic privilege management ensures that if the privileges associated with a role are
modified, all the users who are granted the role acquire the modified privileges
automatically and immediately.
selective availability of privileges, and

Roles can be enabled and disabled to turn privileges on and off temporarily. Enabling a
role can also be used to verify that a user has been granted that role.
granting through the operating system
Operating system commands or utilities can be used to assign roles to users in a database
in some operating systems.
Roles are disabled in PL/SQL subprograms. The owner of a PL/SQL subprogram
declared with definer's rights must have the privileges required for the subprogram
granted directly and not through a role. For a subprogram with invoker's rights, roles are
enabled unless the subprogram is invoked directly or indirectly from a definer's-right
subprogram.
There are several roles that are defined automatically for Oracle Databases when you run
database creation scripts. CONNECT is granted automatically to any user who is created
with Oracle Enterprise Manager.
SELECT_CATALOG_ROLE is provided for accessing data dictionary views and packages.
(This role is deprecated in favor of the SELECT ANY DICTIONARY system privilege.) The
DBA role includes nearly all privileges and should not be granted to nonadministrators.

Graphic
The table contains details for the CONNECT, RESOURCE,
SCHEDULER_ADMIN, DBA, and SELECT_CATALOG_ROLE roles.
Other roles that authorize you to administer special functions are created when that
functionality is installed. For example, XDBADMIN contains the privileges that are required
to administer the XML database if that feature is installed. AQ_ADMINISTRATOR_ROLE
provides privileges to administer advanced queuing. HS_ADMIN_ROLE includes the
privileges needed to administer heterogeneous services.
You must not alter the privileges granted to these functional roles without the assistance
of Oracle Support because you may inadvertently disable the needed functionality.
Prior to Oracle Database 10g Release 2, the CONNECT role had the privileges ALTER
SESSION, CREATE SESSION, CREATE CLUSTER, CREATE SYNONYM, CREATE DATABASE
LINK, CREATE TABLE, CREATE SEQUENCE, and CREATE VIEW. Now the CONNECT role
has only the CREATE SESSION privilege, and all other privileges are removed.
Although the CONNECT role has frequently been used when provisioning new accounts in
Oracle Database, simply connecting to the database does not require all those privileges.
Making this change enables new and existing database customers to enforce good
security practices more easily.

The rstrconn.sql script located in the $ORACLE_HOME/rdbms/admin directory is


provided to restore the old privileges to the CONNECT role. After a database upgrade or
new database creation, this script can be used to grant the privileges removed from the
CONNECT role.
The secure and recommended method is to create a new role containing only the
required privileges. Then determine which users or database roles have the CONNECT
role and grant the new role to these users or roles.
The DBA_CONNECT_ROLE_GRANTEES view enables you to quickly determine which users
have the CONNECT role.

Question
What are features of the CONNECT role?
Options:
1.

The rstrconn.sql script located in the $ORACLE_HOME/rdbms/admin directory is


provided to restore the old privileges to the CONNECT role

2.

It has the ALTER SESSION, CREATE SESSION, CREATE CLUSTER, CREATE


SYNONYM, CREATE DATABASE LINK, CREATE TABLE, CREATE SEQUENCE, and
CREATE VIEW privileges

3.

The DBA_CONNECT_ROLE_GRANTEES view enables you to quickly note which users


have the CONNECT role

4.

For security reasons, it must be manually granted to users created with Enterprise
Manager

Answer
Option 1: This option is correct. The rstrconn.sql script located in the
$ORACLE_HOME/rdbms/admin directory is provided to restore the old privileges
to the CONNECT role. After a database upgrade or new database creation, this
script can be used to grant the privileges removed from the CONNECT role.
Option 2: This option is incorrect. Prior to Oracle Database 10g Release 2, the
CONNECT role had these privileges. Now the CONNECT role has only the CREATE
SESSION privilege, and all other privileges are removed.
Option 3: This option is correct. The DBA_CONNECT_ROLE_GRANTEES view
enables you to quickly note which users have the CONNECT role. This view
contains GRANTEE, PATH_OF_CONNECT_ROLE_GRANT, and ADMIN_OPT
columns.

Option 4: This option is incorrect. The CONNECT role is granted automatically to


any user who is created with Oracle Enterprise Manager.
Correct answer(s):
1. The rstrconn.sql script located in the $ORACLE_HOME/rdbms/admin directory
is provided to restore the old privileges to the CONNECT role
3. The DBA_CONNECT_ROLE_GRANTEES view enables you to quickly note which
users have the CONNECT role

2. Using proxy authentication with roles


The usage of proxy authentication with roles include these two procedures.

Code
ALTER USER phall
GRANT CONNECT THROUGH appsrv
WITH ALL ROLES EXCEPT hr_manager;
ALTER USER phall
GRANT CONNECT THROUGH appsrv
WITH NO ROLES;
ALTER USER phall
GRANT CONNECT THROUGH appsrv
WITH ALL ROLES EXCEPT hr_manager;
The default authentication allows a proxy to activate all roles that are granted to a user. If a
user is allowed only certain privileges through a specific application, you can limit the roles
that the proxy can activate.
ALTER USER phall
GRANT CONNECT THROUGH appsrv
WITH NO ROLES;
If the user does not require any privileges in a specific application, the proxy user can be
prevented from activating any roles that may be granted to the user for use in other
applications.
An enterprise role allows the administrator to collect the access requirements for a job
role or function into a named role that can span the enterprise. Roles defined in each
database are tailored to the applications and data residing in that database. Enterprise
roles require the use of Oracle Internet Directory, which is also known as OID.

HRDB has a MANAGER role that allows a manager to modify certain fields of the employee
records that are assigned to the managers. BUGDB has a USER role that allows a user to
create bugs and update bugs that the user created. The PRACTICE_MGR enterprise role
is assigned a set of global roles: MANAGER in HRDB, USER in BUGDB, and PARTICIPANT
in PROJDB. Each global role is defined in the local database, so the practice manager will
get different privileges in each database.
HRDB has an EMPLOYEE role that allows every employee to view and modify certain
records, such as a profile. BUGDB has a DEVELOPER role that is allowed to update any
bug that is assigned to the developer. The PROGRAMMER enterprise role is assigned
EMPLOYEE and DEVELOPER global roles.

Note
All users assigned the same enterprise role receive the same privileges.
An enterprise role is an OID directory structure that can contain global roles on multiple
databases. The enterprise role is granted to enterprise users. When an enterprise user
attempts to connect to the database, the enterprise directory is queried to obtain any
global roles associated with the user.
The global role is defined locally in the database and granted privileges and roles. You
cannot grant the global role to a user or a role in the database. An enterprise user can be
authorized to use the role only by an enterprise directory service.
Use EM Database Control Enterprise User Security to create an enterprise role. This
creates a container for global roles. An example is HRACCESS_ROLE.

Graphic
The Create Enterprise Role : HRACCESS_ROLE page consists of a Name field
with HRACCESS_ROLE entered in it. This page also contains the DB Global
Roles and Grantees tabbed pages. The DB Global Roles tabbed page contains a
table with Name as HR_ACCESS and the type of Database as p1orcl.
To create mapping to a global role, on the Enterprise User Security page of the Database
control, perform the following steps:

Graphic
This page contains the links Manage Enterprise Domains, Manage Databases,
Manage Enterprise Users, Manage User Defined Enterprise Groups, and OID
Realm Administration.

1. Click the Manage Enterprise Domains link.


2. On the Manage Enterprise Domains page, select the domain and click Configure.
In this example, the domain selected is OracleDefaultDomain. It is listed in a table with columns Select,
Name, Databases, User-Schema Mappings, Enterprise Roles, Proxy Permissions, and Domain Admins.
3. On the Configure Domain : OracleDefaultDomain page, click the Enterprise Roles tab.
Currently the Databases tabbed page is opened.
4. On the Enterprise Roles tabbed page, click Create.
This page also contains the Ok and Cancel buttons in addition to the Create button.
5. Enter the name and click Add.
HRACCESS_ROLE is entered in the Name field.
6. On the Search And Select : Database Global Roles page, select the database and enter the credentials
for a user with access to DBA_ROLES. Then select the roles and click Select.
You provide the details in the Database drop-down list and User Name and Password fields. In this
example, the orcl2 database is selected. The user name entered is ksmith and the corresponding
password is also entered.
And you select the role by selecting the checkbox in the Select column against the relevant role name in
the Name column of the table in the page.
The EM Database Control Enterprise User Security tool enables you to associate an
enterprise role with a user. When the user connects to the database, the global roles
assigned to the enterprise role are enabled for the user.

Graphic
The Create Enterprise Role : HRACCESS_ROLE page is opened.
To assign an enterprise user to an enterprise role, perform the following steps:
1. on the Create Enterprise Role : HRACCESS_ROLE page, click the Grantees tab, and then click
Add
2. on the Select : Users or Groups page, enter the user search string, and click Go
In this example, the string cn=users, dc=easynomadtravel,dc=com is selected from the Search Base
list.
3. browse and select a user and click Select
4. on the Create Enterprise Role : HRACCESS_ROLE page, click Continue, and
5. on the Configure Domain : OracleDefaultDomain page, click Ok

Assigning the enterprise role to many users by using this method can be tedious.
Enterprise roles can be assigned to groups of users. Use the Oracle Identity Management
Self Service console to create a group and assign users to the group. Then use EUS
pages to assign the group to the role by using the cn=Groups node instead of the
cn=Users node.

Graphic
The Create Group section under the Directory tabbed page of the Oracle Identity
Management page is currently opened. It contains the fields Name, Display
Name, and Description. Sales is entered in the Name and the Display Name
fields. The description is "Members of the Sales Team". The Group Visibility field
has two selectable radio buttons Public and Private. In this example, Public is
selected.

3. Securing objects with procedures


When the built-in authorization mechanisms are not sufficient, an object-oriented
approach is useful. Program units, procedures, and functions in the database, by default,
run with definer's rights. This means that the program unit executes with the privileges of
the owner of the unit.
The HR application owner has a Medical_History table with very strict access
controls. The HR user creates PL/SQL procedures and functions to implement the allowed
access.
HR can grant the EXECUTE privilege on these program units to authorize certain users to
perform only the actions that are implemented in the procedures. Users can access the
table only through the procedures because they have not been granted any other object
privileges. The procedures successfully access the table because they run with the
privileges of HR.
Program units can also run with invoker's rights. In this case, the procedure executes with
only the privileges of the user that executes the procedure. This is useful for procedures
that are very general and owned by SYS. An example is the DBMS_LOB package that
provides the LOB access routines that can be called by any user. But the invoker must
have privileges to access the LOB.
Often users are authorized to access certain objects only through an application that can
control and check their actions.
Before Oracle9i, password-enabled roles offered limited control because the password
had to be supplied by the user or embedded in the application. If users have the
password, they can enable the role at any time. If the password is embedded (hidden in
the application code), there are several utilities that can easily reveal the password.

The secure application role is enabled only through a package. The server checks the
calling stack to ensure that the proper package is being used so that it cannot be
spoofed. To enable a secure application role, the associated procedure must be called,
which controls whether the role is enabled. The procedure can make additional checks
and get information about the user's environment by using a call to
SYS_CONTEXT('USERENV',nnn), where nnn can be, for example, IP_ADDRESS or
PROXY_USER.
The EXECUTE privilege is granted on the package only to the application. So even if users
know the details of the package, they cannot enable the role, except through the
application.

4. Implementing a secure application role


Roles grant authorizations to the authenticated user. You may require additional
validation. For example, access may be restricted by time of day or client IP address.
Because a secure application role is a role implemented by a package, the package can
do the desired validation.
Besides limiting the privileges of the application server, the secure application role
prevents users from accessing data outside an application. They are forced to work within
the framework of the application privileges that they have been granted.
To create a secure application role, perform the following steps:
1. Create the secure application role.
2. Create the package that sets the role. When creating the package, create the package specification and
the package body.
3. Grant the execute privilege on the package so that the application server can set the role for the
application user.
4. Write the application server code that sets the role by calling the package just created.
Because the package does not need to exist when the CREATE ROLE command is issued,
step 2 can be performed before step 1.

Question
During which step of implementing a secure application role is the AUTHID
CURRENT_USER clause used to define procedures with invoker's rights?
Options:

1.

Creating the secure application role

2.

Creating the package that sets the role

3.

Granting the execute privilege on the package

4.

Writing the application server code that sets the role by calling the package

Answer
Option 1: This option is incorrect. This is the first step in implementing a secure
application role. At this stage, you use the CREATE ROLE command to identify the
package that sets the role.
Option 2: This option is correct. This is the second step in the process and
consists of creating the package specification and the package body. At this stage,
you use the AUTHID CURRENT_USER clause to define procedures with invoker's
rights. It applies only to packages and stand-alone procedures and functions.
Option 3: This option is incorrect. This is the third step in the process. At this
stage, the execute privilege is granted on the package. For example, the
application server can connect as a particular user and then set the role after it
starts the user's session.
Option 4: This option is incorrect. This is the final step in the process. To set the
role for a user, the application server calls a procedure in the package referenced
in the CREATE ROLE command. The procedure is called after the application
server establishes a session for the user.
Correct answer(s):
2. Creating the package that sets the role
The CREATE ROLE command identifies the package that sets the role. The package does
not need to exist when the role is created. When the procedure is called to set the
OE_SALES_REP role, the calling stack is checked for the SEC.OE_ROLES package.

Code
CREATE ROLE oe_sales_rep
IDENTIFIED USING sec.oe_roles;

Question
What should be considered when implementing a secure application role?
Options:

1.

Secure application roles limit the privileges of the application server

2.

No additional validation is required

3.

Secure application roles prevent users from accessing data outside an application

4.

The package needs to exist when the CREATE ROLE command is issued

Answer
Option 1: This option is correct. Besides limiting the privileges of the application
server, the secure application role prevents users from accessing data outside an
application.
Option 2: This option is incorrect. Roles grant authorizations to the authenticated
user. You may require additional validation. For example, access can be restricted
by time of day or the client IP address.
Option 3: This option is correct. The secure application role prevents users from
accessing data outside an application. They are forced to work within the
framework of the application privileges that they have been granted.
Option 4: This option is incorrect. Because the package does not need to exist
when the CREATE ROLE command is issued, you can create the package that sets
the role before creating the role.
Correct answer(s):
1. Secure application roles limit the privileges of the application server
3. Secure application roles prevent users from accessing data outside an
application
Because procedures with definer's rights always execute with the privileges of the owner,
secure application roles can be enabled only inside procedures with invoker's rights.
The AUTHID CURRENT_USER clause defines procedures with invoker's rights. It applies
only to packages and stand-alone procedures and functions. For a package, it must be
coded in the specification of the package and cannot be coded in the procedures or
functions of the package.

Code
CREATE OR REPLACE PACKAGE oe_roles
AUTHID CURRENT_USER
IS
PROCEDURE set_sales_rep_role;
END;
/

Sometimes, a secure package may need to access a table to retrieve all the roles that
can be enabled. This table must be accessed by a definer's rights procedure called from
the secure procedure that sets the role. Create a definer's rights package to return a list
of roles from the table (via an open cursor) to the invoker's rights procedure. Then fetch
from the cursor the list of roles to be enabled.

Code
CREATE OR REPLACE PACKAGE oe_roles
AUTHID CURRENT_USER
IS
PROCEDURE set_sales_rep_role;
END;
/
The package that enforces the secure application role selects from the APP_ROLES table.
The APP_ROLES table validates users in the application by ensuring that the user
enabling the role is connecting from a valid IP address. It contains the following columns:

Code
USERNAME
PHALL
PHALL

ROLE
SALES_REP
SALES_REP

IP_ADDRESS
134.43.51.114
134.43.51.120

USERNAME
USERNAME contains the name of the user who is trying to enable the role.
ROLE, and
The name of the role that the user wants to enable is available in the ROLE column.
IP_ADDRESS
The IP_ADDRESS column consists of the client's address that can enable the row.
In this example, if the PHALL user can enable only the SALES_REP role from the IP
addresses 134.43.51.114 and 134.43.51.120, the table would contain these details.

Code
USERNAME
PHALL
PHALL

ROLE
SALES_REP
SALES_REP

IP_ADDRESS
134.43.51.114
134.43.51.120

The WHERE clause includes the following criteria:

Code
CREATE OR REPLACE PACKAGE BODY oe_roles IS
PROCEDURE set_sales_rep_role
AS
v_id oe.app_roles.id%TYPE;
BEGIN
SELECT
id
INTO
v_id
FROM
oe.app_roles
WHERE sys_context('userenv','current_user')
AND role = 'SALES_REP'
AND ip_address =
sys_context('userenv','ip_address');
dbms_session.set_role('oe_sales_rep');
END;
END;
/
the current user must be named in the table
the user must be a sales representative, and
the user must be logged on from an approved IP address
If the user passes the validation, enable the role by executing
DBMS_SESSION.SET_ROLE. If the user does not pass the validation, the
NO_DATA_FOUND exception is raised, and the role is never enabled.

Code
CREATE OR REPLACE PACKAGE BODY oe_roles IS
PROCEDURE set_sales_rep_role
AS
v_id oe.app_roles.id%TYPE;
BEGIN
SELECT
id
INTO
v_id
FROM
oe.app_roles
WHERE sys_context('userenv','current_user')
AND role = 'SALES_REP'
AND ip_address =
sys_context('userenv','ip_address');
dbms_session.set_role('oe_sales_rep');
END;
END;
/

In this example, the account used by the application server is granted the EXECUTE
privilege on the package. The application server can execute the package to enable the
role when it creates a session for the end user.
The application server connects as the appsrv user and sets the role after it starts the
user's session.

Code
GRANT execute ON oe_roles TO appsrv;
When starting, the application server connects as the APPSRV user and creates a
connection pool. When starting a session for a user, the application server gets a
connection from the pool.
To set the role for a user, the application server calls a procedure in the package
referenced in the CREATE ROLE command. The procedure is called after the application
server establishes a session for the user.

Code
sec.oe_roles.set_sales_rep_role;
Do not grant the secure role to the user as a default role. If the role is granted to the user,
it is enabled at login if the default role is set to all. If there are roles that should be
enabled for users at login, this command disables the secure role.

Code
ALTER USER phall DEFAULT ROLE ALL EXCEPT oe_sales_rep;
Data dictionary views include the following roles:

Code
SQL> SELECT *
2
FROM dba_application_roles
3
WHERE ROLE = 'OE_SALES_REP';
ROLE
SCHEMA PACKAGE
------------- ------- -------OE_SALES_REP SEC
OE_ROLES
SQL>

SESSION_ROLES and
After the application server sets the role, the role appears in the SESSION_ROLES data
dictionary view.
DBA_APPLICATION_ROLES
The data dictionary view called DBA_APPLICATION_ROLES lists all the secure application
roles in the database. The example displayed selects the role previously created. The
SCHEMA column contains the owner of the package. Roles are not owned by a schema.

Summary
In this topic, you've learned how roles and privileges can be used, and how to use secure
application roles.

Creating an Application Context


Learning Objective

After completing this topic, you should be able to

recognize how an application context is used

1. Description of application context


An application context is a memory container with read-only attributes. It can be
populated only by a named package. You can use these attributes explicitly or implicitly in
your application. Using an application context is like writing down an often-used phone
number and keeping it next to your phone, where you can find it easily, rather than
looking it up every time you need it.
A context has an allocated area of memory called a namespace. The context or
namespace has named attributes. Each attribute can hold a text string value. In some
programming languages, this is known as an associative array.

Graphic
The application context reads a PL/SQL program after being set by a PL/SQL
package.
The application context namespace identifies the application context. For example, you
may have the HRAPP and OEAPP namespaces that are used with the Human Resources
and Order Entry applications respectively. Multiple namespaces enable you to use the
same attribute's name in a different namespace without interfering with other

namespaces. For example, the HRAPP and OEAPP application contexts can each have an
attribute named ID that contains a different value in each context.
Context memory accessed locally is allocated from the fixed portion of program global
area, also known as PGA, which belongs to each server process. This memory allocation
is not subject to the effects of the PGA_AGGREGATE_TARGET parameter.
A namespace is a set of names in a naming system where all names are unique. Each
context is created in its own namespace. In the example, each attribute of the HRAPP
context is unique within the HRAPP context.

Code
CREATE CONTEXT hrapp
USING hr_context;
dbms_session.set_context (
'hrapp', 'emp_id', v_emp_id );
CREATE CONTEXT hrapp
USING hr_context;
When a context is created, a memory area is allocated, and the context is given a name. A
package is associated with the context at creation. This package is the only package that
is allowed to set the attributes in a context.
In the example, the HRAPP context is created, and a package is named that has exclusive
rights to set the attributes of the context. In the example, the package is HR_CONTEXT.
The CREATE CONTEXT command is used to create a context in the namespace and
associate a package with the context.
dbms_session.set_context (
'hrapp', 'emp_id', v_emp_id );
SET_CONTEXT is used to create attributes or set the values of them. If the attribute does
not exist, it is created. In the example, the emp_id attribute is created in the HRAPP
context, and the value of v_emp_id is assigned.
Although the main benefit of using application contexts is improved performance,
contexts are used with Oracle Database security features, such as Virtual Private
Database, also referred to as VPD, or fine-grained access control, referred to as FGAC.
With application context, you can write applications that use the attributes of the
application context to perform the following:

Authorize users when they log on. For example, you can verify that the user is connecting
through a specific computer by verifying the user's IP address. You would use the USERENV
context to access the user's current IP address.

Set context attributes that are used by FGAC policies. Session properties can be used to limit the
rows that the user can access. In an order-entry application, customers can access only their own
orders by setting a context attribute with the current user's customer number. Because of the way
the context is set and used, you can implement FGAC without changing the application.

Set the attributes that are used in the application. In this situation, set the attributes as part of the
context, rather than accessing the attributes from a table. For example, if the user's employee
number is used frequently in the application, you can create a context attribute that contains the
employee number, rather than selecting the employee number from a table.
The application developer or security developer writes a package that assigns values to
the context attributes. The attributes of the context can be set only with this package. This
is the package that is associated with the context when the context is created. This
package can be called by the application or a logon trigger. The package sets the
attributes that are used for that session. These must be attributes that are frequently used
by the application.
The benefit of the context comes from caching these values in memory and not having to
perform SQL or system callouts to retrieve them.
Each application can have its own application-specific context. For example, the context
attributes for a human resources application can include position, organizational unit, and
country, whereas context attributes for the order-entry system may be customer ID and
name.
Applications can use multiple contexts, and a context can be used by multiple
applications.
A special context is the built-in USERENV context. The USERENV context is populated with
values that are commonly found in the V$SESSION and V$PROCESS views and is
available to all applications.

Question
Which statements accurately describe application context?
Options:
1.

It is a memory container with read-only attributes

2.

It can be populated by only the USERENV context

3.

Its namespace identifies the application context

4.

A context can't be used by multiple applications

Answer
Option 1: This option is correct. An application context is a memory container with
read-only attributes. You can use these attributes explicitly or implicitly in your
application.
Option 2: This option is incorrect. An application context can be populated only by
a named package.
Option 3: This option is correct. A context has an allocated area of memory called
a namespace. The context or namespace has named attributes. Each attribute
can hold a text string value.
Option 4: This option is incorrect. Applications can use multiple contexts, and a
context can be used by multiple applications.
Correct answer(s):
1. It is a memory container with read-only attributes
3. Its namespace identifies the application context
A context can be classified by the source of the data values that it contains. The value
that is assigned to the context attribute can have different sources.
The built-in context called USERENV includes the following types of attributes:

client properties, such as the IP address of the client computer

user properties, such as the proxy, session, and operating system user

authentication methods, such as the type (which indicates whether the user is authenticated
through the database), the operating system, the network, or a proxy, and
national language support, also called NLS, settings, such as NLS_TERRITORY
You can set attributes that are stored in a context from any database object. For example,
an EMPLOYEES table can include cost center, title, signing authority, and other information
that is useful for row-level security. Also values returned from procedures and functions
can be used. For example, use a function that returns the employee ID to assign a value
to the context attribute.
An externally initialized application context is characterized by attributes and values that
are initialized through external resources, such as an OCI call, a job queue process, or a
database link.

It provides the following:

for remote sessions, automatic propagation of context values that are in an external initialized
context namespace

for job queues, restoration of context values that are in an externally initialized context
namespace, and

for OCI, a mechanism to initialize context values that are in an externally initialized context
namespace
Any client program can initialize this context by making OCI calls, and there are logon
event triggers that can verify the values. It is up to the application to interpret and trust the
values of the attributes. This type of context is created with this command.
Note that with an externally initialized application context, the middle-tier server can
actually initialize context values on behalf of database users. Context attributes are
propagated for the remote session at initiation time, and the remote database accepts the
values if the namespace is externally initialized.

Code
CREATE CONTEXT external USING ext_package INITIALIZED
EXTERNALLY;
Many organizations centralize user information and user management in a Lightweight
Directory Access Protocol or LDAP based directory, such as Oracle Internet Directory,
referred to as OID. Application context attribute values can be stored in OID. This type of
context is created in the database with this command.

Code
CREATE CONTEXT hrgapp USING hr_g_context INITIALIZED
GLOBALLY;
When an enterprise user connects to the database, the attributes defined in the global
context of that user's OID entry are placed in the named application context. The global
context named in the preceding example is HRGAPP. The attributes that are available are
dependent on the attributes defined in the LDAP directory. The SYS_CONTEXT function
can be used to access the attributes of the context.
The HRGAPP context and the TITLE attribute must be added to the user's OID entry in
the OracleDBAppContext object.

Code
SYS_CONTEXT('HRGAPP','Title')

Question
Using a function that returns the employee ID to assign a value to the context
attribute is an example of what type of context?
Options:
1.

Built-in context

2.

Externalized application context

3.

Local application context

4.

Global application context

Answer
Option 1: This option is incorrect. The built-in context called USERENV includes
attributes such as client properties, user properties, authentication methods, and
national language support settings.
Option 2: This option is incorrect. An externally initialized application context is
characterized by attributes and values that are initialized through external
resources, such as an OCI call, a job queue process, or a database link.
Option 3: This option is correct. You can set attributes that are stored in a context
from any database object. Also, values returned from procedures and functions
can be used. For example, use a function that returns the employee ID to assign a
value to the context attribute.
Option 4: This option is incorrect. When an enterprise user connects to the
database, the attributes defined in the global context of that user's OID entry are
placed in the named application context.
Correct answer(s):
3. Local application context
If an LDAP inetOrgPerson object entry exists for the user, the connection also
retrieves all the attributes from inetOrgPerson and assigns them to the
SYS_LDAP_USER_DEFAULT namespace.

Code

SYS_CONTEXT('SYS_LDAP_USER_DEFAULT','telephoneNumber')

2. Implementation of a local context


To build an application context, perform the following steps:
1. Create an application context. The application context is associated with the package in step 2.
This ensures that the context is changed only through the package.
2. Create a PL/SQL package that sets the attributes in the application context.
3. Call the package from the application or in a logon trigger.
4. Read the application context attributes in your application.

Note
Steps 1 and 2 can be reversed.
In this example, an application context, HRAPP, is created by using the hr_context
package. The context holds an emp_id attribute that has the value of employee_id for
each user that logs in. The value is retrieved from the HR.EMPLOYEES table on the basis
of the user's e-mail address. It is assumed for this example that the user's database
account name is the same as the user's e-mail ID.

Code
CREATE CONTEXT hrapp USING hr_context;
To perform this task, use the CREATE CONTEXT statement. Each context must have a
unique attribute and must belong to a namespace. So context names must be unique
within the database, not just within a schema. Contexts are always owned by the SYS
schema.

Code
CREATE CONTEXT hrapp USING hr_context;
In this context creation example,

Code
CREATE CONTEXT hrapp USING hr_context;

hrapp is the context namespace and

HR_CONTEXT is the trusted package that can set attributes in the context namespace
In the example code, the package and security objects are created by a user designated
for this purpose.

Code
CREATE CONTEXT hrapp USING hr_context;
After you have created the context, you can set or reset context attributes by using the
DBMS_SESSION.SET_CONTEXT package. The values of the attributes that you set
remain either until you reset them or until the user ends the session.
You can set the context attributes only in two locations:

Code
CREATE CONTEXT hrapp USING hr_context;

inside a procedure of the trusted package that you have named in the CREATE CONTEXT
statement and
inside the function named in the policy
This prevents a malicious user from changing context attributes without proper attribute
validation.

Code
CREATE CONTEXT hrapp USING hr_context;
Administration of application contexts is integrated in Enterprise Manager, also referred to
as EM, with a graphical user interface for managing application contexts, FGAC policies,
and Oracle Label Security policies. You can use EM to create a context and associate it
with a PL/SQL package.
Create a PL/SQL package with functions that sets the context for your application. This
example creates the HR_CONTEXT package. The package sets the EMP_ID attribute of
the HRAPP context. The session username is used to get the employee ID, and
SET_CONTEXT is used to set a context attribute.

Code

CREATE OR REPLACE PACKAGE hr_context IS


PROCEDURE set_emp_id;
END;
/
CREATE OR REPLACE PACKAGE BODY hr_context IS
PROCEDURE set_emp_id
IS
v_emp_id NUMBER;
BEGIN
SELECT employee_id INTO v_emp_id FROM hr.employees
WHERE email =
SYS_CONTEXT('USERENV', 'SESSION_USER');
DBMS_SESSION.SET_CONTEXT
('hrapp', 'emp_id', v_emp_id);
EXCEPTION
WHEN no_data_found THEN
DBMS_SESSION.SET_CONTEXT
('hrapp', 'emp_id', 0);
END;
END;
/
Although a logon trigger is not required (the application can initialize the context at any
time), it is highly recommended because the user's context must be set before the user
accesses any data.
The example displays a logon trigger that affects only a single user or schema. If all
application users are connecting as PHALL, this is an effective method of setting the
context.

Code
CREATE OR REPLACE TRIGGER hr_context_logon
AFTER LOGON ON phall.SCHEMA
BEGIN
hr_context.set_emp_id();
END;
/
If all users are connecting with their own usernames, the alternative logon trigger can be
used.

Code
CREATE OR REPLACE TRIGGER hr_context_logon
AFTER LOGON ON DATABASE

BEGIN
hr_context.set_emp_id();
END;
/
Access application context attributes and use them where they are needed in your
application. The name of the context and the attribute are the two arguments used to
return an attribute value.

Code
SELECT * FROM departments
WHERE manager_id =
sys_context('hrapp','emp_id');
The SYS_CONTEXT PL/SQL function returns the values of context attributes, which
includes the following:

Code
sys_context ('userenv', 'ip_address')
sys_context ('hrapp', 'emp_id')

built-in attributes from the USERENV context, which contains session properties and

user-defined attributes from user-defined contexts


The SYS_CONTEXT PL/SQL function has this syntax, where the context is the name of the
application context, and attribute is the name of the attribute in the context.

Code
sys_context ('userenv', 'ip_address')
sys_context ('hrapp', 'emp_id')

Syntax
SYS_CONTEXT ('context', 'attribute')
These examples describe the SYS_CONTEXT being used to return the following
information:

Code
sys_context ('userenv', 'ip_address')
sys_context ('hrapp', 'emp_id')

IP address of the client computer by using the IP_ADDRESS attribute of the built-in USERENV
context and
The IP address of the client computer is returned by using this code:
sys_context ('userenv', 'ip_address')
Code
sys_context ('userenv', 'ip_address')
sys_context ('hrapp', 'emp_id')

employee ID from the HRAPP context


Employee ID is returned by using this code:
sys_context ('hrapp', 'emp_id')
Code
sys_context ('userenv', 'ip_address')
sys_context ('hrapp', 'emp_id')

Summary
In this topic, you've learned how an application context is used.

Implementing Application Context


Learning Objective

After completing this topic, you should be able to

recognize how to implement an application context accessed globally

1. Access an application context globally

The memory for the application context is allocated from the session's program global
area, also referred to as PGA, by default. In many application architectures, the middletier application is responsible for managing connection pooling for application users.
Users authenticate themselves to the application. The application then uses a single
identity to log in to the database and maintains all connections. In a connection-pooling
environment, usually any user can use any connection.
The application decides the connection that a user request can use. In this environment,
it is not possible to maintain application attributes by using session-dependent secure
application context because the context is private to each session, and because of the
sessionless model of the application, any user can use any session.

Graphic
The Application context in SGA is EMP ID = 101. It is accessed in two programs in
two different database sessions. They are PL/SQL program A in User database
session 1 and PL/SQL program B in User database session 2.
The application context accessed globally is a type of secure application context that can
be shared among trusted sessions. It can be shared because the memory for the context
is allocated from the system global area, referred to as SGA.
Middle-tier applications use globally accessed application contexts to manage application
attributes securely and globally. Global application contexts with connection pooling allow
multiple connections to access one or more contexts, instead of setting up an application
context for each user session.
Globally accessed application contexts provide additional flexibility for web-based
applications. They also provide enhanced performance through the reuse of common
application contexts among multiple sessions, instead of setting up application contexts
for each session.
Application contexts accessed globally provide performance improvements through
connection reuse. These application contexts are initialized once, instead of being
initialized for each session individually.

Note
The application must initialize the context.
The middle tier sets the application context for each session. The context accessed
globally allows the middle tier to store various application context definitions in a central
place in the SGA and apply the context to a user session at session-creation time. This
then becomes that session's driving context. This also reduces the setup time of the user
session when the application is using connection pooling.

A context accessed globally cannot be initialized from OID or an external source. So any
context accessed globally must be a local context accessed globally.
To support connection pooling managed by middle-tier applications, the DBMS_SESSION
interface gives the application the ability to add a client identifier for each application
context. The application can manage the context globally, whereas each client notes only
its assigned application context.
The application must test input to prevent a malicious user from injecting a call to
DBMS_SESSION or any SQL injection attempt. Because DBMS_SESSION is granted to
PUBLIC, such an injection can allow the user unauthorized privileges. By default, a
context is not accessed globally.

Note
A context accessed globally is not available in the Real Application Clusters, also
called RAC, environment for connections that span instances. The context
accessed globally is stored in the shared pool of one instance and is not available
in the other instances of the cluster.
Consider an example of actions being performed. Certain actions are taken by the user,
and others are taken by a program running on the application.
The application server starts up and builds its connection pool by establishing multiple
connections to the database as the APPSMGR user. User PHALL logs in to and is
authenticated by the application server.

Graphic
The boxes in the flow chart list 9 actions performed. The first box lists actions
Logs in, Makes another request, and Logs out performed by the user PHALL as
the second, sixth, and eighth step. The second box lists steps 1, 3, 4, 5, 7, and 9,
which are performed by the application server, which connects to the user PHALL
and the database. They are Builds connection pool, Establishes session,
Processes request, Completes request, Processes second request, and Clears
context respectively.
The application server establishes a session for the request from PHALL by performing
the following functions:

using a connection from the connection pool

calling SET_IDENTIFIER to assign a session client identifier for the PHALL username

setting the application context, and

saving the client identifier in the browser of PHALL as part of a cookie or maintaining the client
identifier within the application server
The application server processes the request of PHALL. When the application reads
contexts, it does not include the client identifier because the SET_IDENTIFIER call has
already identified the session.
When the application server finishes the request of PHALL, it issues a
CLEAR_IDENTIFIER call and returns the connection to the pool.
The PHALL user makes another request. The application starts differently because there
is a cookie identifying the current context:

the session client identifier is retrieved from the cookie or the application server storage
the client identifier is used in the SET_IDENTIFIER call after the connection is obtained from the
pool, and
the application runs as before, accessing the context from the previous call
PHALL logs out from the application. The application server issues CLEAR_CONTEXT to
clear out the application context.
All SYS_CONTEXT calls within this database session return only application context
values belonging to the client session for example, SYS_CONTEXT('HRAPP','ID') returns
PHALL.

2. PL/SQL package and procedures


Use the programs in the DBMS_SESSION package to perform these functions:

Code
set_context(context, attribute, value );
dbms_session.set_context
('hrapp', 'emp_id', v_emp_id );

dbms_session.set_identifier(client_id);
dbms_session.set_identifier(12345);

maintain application contexts

list application contexts, and

maintain client identifiers that are used with global application contexts
The procedures and functions in DBMS_SESSION include only those that are related to
application contexts.
The first SET_CONTEXT example sets the EMP_ID attribute in the HRAPP context to the
value in the V_EMP_ID PL/SQL variable. Because the client identifier is not included as
an argument, this context is not being shared.

Code
set_context(context, attribute, value );
dbms_session.set_context
('hrapp', 'emp_id', v_emp_id );
The second example sets a session client identifier for PHALL, enabling the session to
access a context accessed globally.

Code
dbms_session.set_identifier(client_id);
dbms_session.set_identifier(12345);
The SET_IDENTIFIER procedure sets an identifier that can be used to share a global
context. It has this specification.
In this specification, the client_id is the identifier being set for this session. This
identifier is arbitrary and it has no relationship with the session_id username. The
application chooses the identifier. Because this identifier is often placed in the browser
cookie, it should not be the information that can violate the privacy of the user.
The identifier should be a randomly chosen string or number. If the application code sets
the client identifier with a call to DBMS_SESSION.SET_IDENTIFIER, client_id is
recorded in audit trails and can provide a way to link a user to an action, if the application
maintains a client_id-to-user mapping.

Code
PROCEDURE set_identifier (
client_id VARCHAR2 )

The CLEAR_IDENTIFIER procedure clears the current session identifier that has been
set with DBMS_SESSION.SET_IDENTIFIER. It has no arguments.
The SET_CONTEXT procedure sets a context attribute. It has this syntax.
In this syntax, namespace is the name of the application context, attribute is the
name of the attribute to be set, value is the value to be assigned to the attribute,
username is the username attribute for the application context, and client_id is the
client identifier that identifies a user session to set a context.

Code
PROCEDURE set_context (
namespace VARCHAR2,
attribute VARCHAR2,
value
VARCHAR2,
username VARCHAR2 DEFAULT NULL,
client_id VARCHAR2 DEFAULT NULL )
The CLEAR_CONTEXT procedure clears the attributes in a context. It has this syntax.
In this syntax, namespace is the namespace of the application context that contains the
attribute to be cleared, client_id is the ID of the client that has the contexts, and
attribute is the name of the attribute to be cleared.
If attribute is not included, all contexts for the client are cleared.

Code
PROCEDURE clear_context (
namespace VARCHAR2,
client_id VARCHAR2,
attribute VARCHAR2 DEFAULT NULL )
The LIST_CONTEXT procedure lists the current context namespaces. It has this syntax.
In this syntax, list is a table of records for storing the list of application contexts set in
the current session, where each item in the list includes the namespace, attribute, and
value of the fields.
lsize is the number of entries in the buffer.

Code

PROCEDURE list_context (
list OUT AppCtxTabTyp,
lsize
OUT NUMBER )
The AppCtxTabTyp type has this specification.

Code
TYPE AppCtxRecTyp IS RECORD (
namespace VARCHAR2(30),
attribute VARCHAR2(30),
value
VARCHAR2(4000));
TYPE AppCtxTabTyp IS TABLE OF AppCtxRecTyp
INDEX BY BINARY_INTEGER;
The UNIQUE_SESSION_ID function returns an identifier, which is unique for all sessions
that are currently connected to this database. Multiple calls to this function during the
same session always return the same result. It has this specification.
This identifier is different from the identifier that you can set by using SET_IDENTIFIER.
This identifier is a hexadecimal representation of session_id, also called SID,
serial#, and a sequence number. It can be up to 24 bytes and can consist of
alphanumeric characters.

Code
FUNCTION unique_session_id RETURN VARCHAR2

Question
Which DBMS_SESSION procedure would you use to find all current context
namespaces?
Options:
1.

UNIQUE_SESSION_ID

2.

LIST_CONTEXT

3.

SET_IDENTIFIER

4.

SET_CONTEXT

Answer

Option 1: This option is incorrect. This function returns an identifier, which is


unique for all sessions that are currently connected to this database.
Option 2: This option is correct. This procedure lists the current context
namespaces. It uses the syntax PROCEDURE list_context (list OUT
AppCtxTabTyp, lsize OUT NUMBER).
Option 3: This option is incorrect. This procedure sets an identifier that can be
used to share a global context.
Option 4: This option is incorrect. This procedure sets a context attribute.
Correct answer(s):
2. LIST_CONTEXT

3. Implementing the application context


To implement an application context accessed globally, perform these steps.
Because the application server sets the session client identifier when a session is
established, the application programs that access the application context are coded the
same, whether or not the context is accessed globally. In either case, you do not include
the session client identifier when reading an application context.
These instructions apply only to application contexts that are preserved between
database connections. For a stateless session, you can use an application context
without accessing it globally.

Graphic
Four steps are depicted in the diagram. Creating an application context, modifying
the program, modifying the application program, and creating or modifying the
application program. When modifying the program or the application program, you
set the session client identifier and clear the client identifier after request ends.
Additionally, when modifying the program, you also set the application context.
The SET_IDENTIFIER procedure sets an arbitrary value as CLIENT_ID. This value is
used to identify a user. A user can receive the same client identifier every time the user
connects or it can be unique every day or every hour. When you decide on the
assignment of the client identifier, consider how cookies can be intercepted and possibly
used to hijack user sessions or spoof user authentications.
The client identifier must never contain any private or personal information that can be
used to steal a user's identity. It is essential that the database trust the identifier from the

application server. A secure application role enabled by the application server together
with the identifier forms a defense-in-depth solution.
This example creates the HRAPP application context that is initialized in the HR_CONTEXT
package. You must indicate that the application context is accessed globally.
Create the context by using this context. The ACCESSED GLOBALLY clause indicates that
the context can be accessed from multiple sessions.

Code
CREATE CONTEXT hrapp
USING hr_context ACCESSED GLOBALLY;
When the user connects to the application server, the application server uses a
connection from its connection pool to connect that user to the database. After the
connection is obtained, the application server checks whether the user has already
established a session. It checks for the cookie containing the session client identifier.
If there is no client identifier, the application server establishes the session by performing
these functions:

Code
dbms_session.set_context
(context, attr, value, username, client_id);
dbms_session.set_context
('hrapp','id','phall','APPSMGR', 12345 );
dbms_session.set_context
('hrapp','dept','sales','APPSMGR', 12345 );
dbms_session.set_identifier( 12345 );
1. Getting a unique client identifier. (For example, the user_id, DN, or other code to identify the
user. This value appears in audit records and trace files.)
Code
dbms_session.set_context
(context, attr, value, username, client_id);
dbms_session.set_context
('hrapp','id','phall','APPSMGR', 12345 );
dbms_session.set_context
('hrapp','dept','sales','APPSMGR', 12345 );

dbms_session.set_identifier( 12345 );

2. Calling the package that sets up the context for this session by using the client identifier. The package
must include the client identifier when it sets the context.
The code to do this is the following:
dbms_session.set_context
(context, attr, value, username, client_id);
dbms_session.set_context
('hrapp','id','phall','APPSMGR', 12345 );
dbms_session.set_context
('hrapp','dept','sales','APPSMGR', 12345 );
Code
dbms_session.set_context
(context, attr, value, username, client_id);
dbms_session.set_context
('hrapp','id','phall','APPSMGR', 12345 );
dbms_session.set_context
('hrapp','dept','sales','APPSMGR', 12345 );
dbms_session.set_identifier( 12345 );

3. Setting the session client identifier by using SET_IDENTIFIER.


The code to do this is the following:
dbms_session.set_identifier( 12345 );
Code
dbms_session.set_context
(context, attr, value, username, client_id);
dbms_session.set_context
('hrapp','id','phall','APPSMGR', 12345 );
dbms_session.set_context
('hrapp','dept','sales','APPSMGR', 12345 );
dbms_session.set_identifier( 12345 );

4. Saving the client identifier in a cookie.

Code
dbms_session.set_context
(context, attr, value, username, client_id);
dbms_session.set_context
('hrapp','id','phall','APPSMGR', 12345 );
dbms_session.set_context
('hrapp','dept','sales','APPSMGR', 12345 );
dbms_session.set_identifier( 12345 );

If there is a client identifier in the cookie, this is not the initial request. The procedure for a
subsequent request is used.
In the application, all SYS_CONTEXT calls within this database session return application
context values belonging to the client session only. For example, the
SYS_CONTEXT('hrapp', 'id') call returns PHALL.

Code
dbms_session.set_context
(context, attr, value, username, client_id);
dbms_session.set_context
('hrapp','id','phall','APPSMGR', 12345 );
dbms_session.set_context
('hrapp','dept','sales','APPSMGR', 12345 );
dbms_session.set_identifier( 12345 );
The steps to handle the subsequent requests are

Code
dbms_session.set_identifier( 12345 );
dbms_session.clear_identifier();
get the client identifier
If there is a session client identifier, this user has already established a session. Therefore,
use the client identifier to ensure that the users access the correct application context. It is
common practice to place the client identifier in the session cookie, but the client identifier

can be stored in the application as well. Do not put the client identifier in the session
cookie.
set the client identifier for this session, and
Set the client identifier for this session because the application context can be shared
among database connections. It does not matter which database connection processes
this request from the user.
clear the identifier
At the end of the request, before the connection is put back into the connection pool, clear
the current client identifier. This ensures that the next session cannot inadvertently use a
left over client identifier to access an inappropriate context.
When the user has completed all requests and wants to end the session, clear the
context that applies to the user's session.
In this example, the attributes for the HRAPP application context for the client identifier
12345 are cleared because the attribute name is not included as the third argument.

Code
EXEC dbms_session.clear_context
('HRAPP', '12345');

Question
When implementing application context accessed globally, during which step
would you include the ACCESSED GLOBALLY clause to indicate that the context
can be accessed from multiple sessions?
Options:
1.

Creating the application context accessed globally

2.

Modifying the program that establishes a session

3.

Modifying the application program that handles subsequent requests in the same
session

4.

Creating or modifying the application program that ends a session to clear the
context

Answer
Option 1: This option is correct. You create an application context using the
syntax CREATE CONTEXT application_context USING package ACCESSED
GLOBALLY;. You must indicate that the application context is accessed globally
using the ACCESSED GLOBALLY clause.

Option 2: This option is incorrect. This is the second step in implementing


application context accessed globally. At this stage, you get a unique value to use
as a client identifier, set the application context, set the session client identifiers,
and save the client identifier in a cookie.
Option 3: This option is incorrect. This is the third step in implementing
application context accessed globally. At this stage, you retrieve the client
identifiers, set the client identifier for the session, and clear the client identifier
when the request ends.
Option 4: This option is incorrect. This is the final step in implementing application
context accessed globally. At this stage, you retrieve the client identifier and clear
the context.
Correct answer(s):
1. Creating the application context accessed globally
The data dictionary includes the following views that are related to application contexts:

Code
SQL> CREATE CONTEXT hrapp USING hr_context;
Context created.
SQL> SELECT *
2
FROM dba_context
3
WHERE namespace = 'HRAPP';
NAMESPACE
--------HRAPP

SCHEMA
-----SYS

PACKAGE
---------HR_CONTEXT

TYPE
---------------ACCESSED LOCALLY

SQL>
ALL_CONTEXT
ALL_CONTEXT describes all context namespaces in the current session for which
attributes and values have been specified by using the DBMS_SESSION.SET_CONTEXT
procedure. It has the same columns as DBA_CONTEXT.
DBA_CONTEXT
DBA_CONTEXT describes all context namespaces that are defined in the database,
regardless of whether any attributes have been specified for them by using the
DBMS_SESSION.SET_CONTEXT procedure. This example uses this view.

DBA_GLOBAL_CONTEXT
DBA_GLOBAL_CONTEXT contains a description of all context information that is accessible
globally. This view is a subset of the information in DBA_CONTEXT.
SESSION_CONTEXT, V$CONTEXT, and GV$CONTEXT, and
SESSION_CONTEXT, V$CONTEXT, and GV$CONTEXT list the attributes and the attribute
values for the current session. The views include NAMESPACE, ATTRIBUTE, and VALUE as
each column.
NAMESPACE is the namespace that the active attribute is in, ATTRIBUTE is the name of the
active attribute, and VALUE is the value of the active attribute. SESSION_CONTEXT and
V$CONTEXT list the same information. GV$CONTEXT is used with Real Application
Clusters, which is also known as RAC.
V$GLOBALCONTEXT and GV$GLOBALCONTEXT
V$GLOBALCONTEXT and GV$GLOBALCONTEXT list the attributes and the attribute values
for application contexts that are accessed globally. The views include NAMESPACE,
ATTRIBUTE, VALUE, USERNAME, and CLIENTIDENTIFIER as columns.
NAMESPACE is the namespace that the active attribute is in, ATTRIBUTE is the name of the
active attribute, VALUE is the value of the active attribute, USERNAME is the username for
the session, and CLIENTIDENTIFIER is the unique session identifier.
GV$GLOBALCONTEXT is used with Real Application Clusters or RAC.

Question
Which data dictionary view describes all context namespaces that are defined in
the database, regardless of whether any attributes have been specified for them
by using the DBMS_SESSION.SET_CONTEXT procedure?
Options:
1.

DBA_GLOBAL_CONTEXT

2.

ALL_CONTEXT

3.

SESSION_CONTEXT

4.

DBA_CONTEXT

Answer
Option 1: This option is incorrect. This view contains a description of all context
information that is accessible globally.

Option 2: This option is incorrect. This view describes all context namespaces in
the current session for which attributes and values have been specified by using
the DBMS_SESSION.SET_CONTEXT procedure.
Option 3: This option is incorrect. This view lists the attributes and the attribute
values for the current session.
Option 4: This option is correct. This view describes all context namespaces that
are defined in the database, regardless of whether any attributes have been
specified for them by using the DBMS_SESSION.SET_CONTEXT procedure. It
contains NAMESPACE, SCHEMA, PACKAGE, and TYPE columns.
Correct answer(s):
4. DBA_CONTEXT
If you try to change the context outside of the package specified in the CREATE CONTEXT
command, you receive an error message stating that you do not have the privilege
required to change the context.
If the SYS_CONTEXT arguments are constants, the SYS_CONTEXT function works much
like a bind variable, enabling cursor sharing.

Code
SQL> exec DBMS_SESSION.SET_CONTEXT ('hrapp', 'emp_id', 0);
BEGIN DBMS_SESSION.SET_CONTEXT ('hrapp', 'emp_id', 0); END;
*
ERROR at line 1:
ORA-01031: insufficient privileges
ORA-06512: at "SYS.DBMS_SESSION", line 78
ORA-06512: at line 1
When you execute a statement, Oracle Database 11g takes a snapshot of the entire
application context. Within the duration of a query, the context remains the same for all
fetches of the query. If you attempt to change the context within a query, the change does
not take effect in the current query. Because a simple application context is allocated per
session, the application context can be versioned.
Versioning is not available for the application context accessed globally. Versioning
returns the SYS_CONTEXT values at a point in time. Because multiple client sessions may
be accessing the same global application context values at any time, versioning is not
possible.

If you try to execute SYS_CONTEXT in a parallel query environment, you receive a query
error.
If SYS_CONTEXT is used inside a SQL function that is embedded in a parallel query, the
function cannot pick up the application context. This is true because the application
context exists only in the user session. To use these features in combination, you must
call SYS_CONTEXT directly from the query.
Application contexts accessed globally are not available in a RAC.
When using an application context for security, the source of the values for the context
attributes must be thoroughly validated. If the source of the context is user input, there the
attribute may be altered to allow unintended access.

Summary
In this topic, you've learned how to implement an application context accessed globally.

Using Roles and Application Contexts


Learning Objectives

After completing this topic, you should be able to

use roles in Oracle Database 11g

use application context in Oracle Database 11g

Exercise overview
You want to implement the secure application role and configure and test an enterprise
role. You've also implemented a local application context named EMP_USER and you
want to test the context by creating a user, logging in as that user, and using
SYS_CONTEXT to verify that the context attributes were properly set. Additionally, you
want to view information about the application context in the data dictionary.
In this exercise, you're required to use the secure application role, create and test an
enterprise role, test application context, and view context information.
This involves the following tasks:

using secure application roles

creating an enterprise role

testing an enterprise role

testing application context

viewing context information

Task 1: Using secure application roles


You have created a secure application role called HR_EMP_MGR that is enabled in the
SEC.APP_ROLES_PKG package. You've also executed the lab_10_01_10.sql script that
ensures that a role can be enabled if the role name, username, and IP address of the
client are in the APP_ROLES table. Connected as SEC, allow anyone to execute the
APP_ROLES_PKG package. Then allow anyone to select from the APP_ROLES table.
Test the configuration by connecting as user PFAY to the ORCL2 database with a
password of "oracle_1." Query the SESSION_ROLES table to see which roles are
enabled. Then use the SEC.APP_ROLES_PKG package to enable the HR_EMP_MGR
role. Query SESSION_ROLES again. Then attempt to change the role to
HR_EMP_MGR.

Steps list
Instructions
1. Type GRANT execute ON app_roles_pkg TO public; and press Enter
2. Type GRANT select ON app_roles TO public; and press Enter
3. Type CONNECT pfay@orcl2 and press Enter
4. Type oracle_1 and press Enter
5. Type SELECT * FROM session_roles; and press Enter
6. Type EXEC sec.app_roles_pkg.set_role('HR_EMP_MGR'); and press Enter
7. Type SELECT * FROM session_roles; and press Enter
8. Type SET ROLE hr_emp_mgr; and press Enter

Task 2: Creating an enterprise role


You want to create an enterprise role in OracleDefaultDomain. Create the HRACCESS
enterprise role. Log in to the ORCL2 database as the SEC user with a password of
"oracle_1" and select the HR_ACCESS role. From the Grantees tab, add a user. Search
for users or groups by typing B in the Name text box. Then select user BSEARS, continue
to the next screen, and confirm the configuration.

Steps list
Instructions
1. Ensure OracleDefaultDomain is selected and click Configure
2. Click the Enterprise Roles tab

Steps list
Instructions
3. Click Create
4. Type HRACCESS in the Name text box and click the scroll bar down arrow
5. Click Add
6. Type sec in the User Name text box, type oracle_1 in the Password text box and click Go
7. Select the HR_ACCESS checkbox and click Select
8. Click the Grantees tab
9. Click Add
10. Type B in the Name text box and click Go
11. Select the cn=BSEARS,cn=users, dc=easynomadtravel,dc=com checkbox and click Select
12. Click Continue
13. Click Ok

Task 3: Testing an enterprise role


Connected as the BSEARS user, who has access to the HRACCESS role, you viewed
the identity information, the roles granted to the session, and queried the
HR.EMPLOYEES table. You now want to do the same connected as another user who
does not have access to the HRACCESS role. Connect as user AKING with a password
of "oracle_1." View the identity information using the SHOW USER command. Return the
SYS_CONTEXT, providing arguments of USERENV and EXTERNAL_NAME, from
DUAL. View the roles granted to the session by querying the SESSION_ROLES table.
Then attempt to select the LAST_NAME and PHONE_NUMBER columns from
HR.EMPLOYEES for employee_id 106. Include any FROM and WHERE clauses on
separate lines.

Steps list
Instructions
1. Type CONNECT aking and press Enter
2. Type oracle_1 and press Enter
3. Type show user and press Enter
4. Type SELECT SYS_CONTEXT('USERENV', 'EXTERNAL_NAME') and press Enter
5. Type FROM DUAL; and press Enter
6. Type SELECT * FROM session_roles; and press Enter
7. Type SELECT last_name, phone_number and press Enter
8. Type FROM hr.employees and press Enter

Steps list
Instructions
9. Type WHERE employee_id = 106; and press Enter

Task 4: Testing application context


As the SEC user, you have implemented a local application context named EMP_USER.
The context contains ID, NAME, and EMAIL attributes, which are obtained from columns
in the HR.EMPLOYEES table. You now want to test the context. Create user KDILKS with
the CREATE SESSION privilege and a password of "oracle1." Log in as KDILKS and use
SYS_CONTEXT to verify that the EMP_USER context attributes are set. Issue the SET
SERVEROUTPUT ON command before issuing any DBMS_OUTPUT statements, and
verify the ID, NAME, and EMAIL attributes respectively.

Steps list
Instructions
1. Type GRANT create session TO kdilks IDENTIFIED BY oracle1; and press Enter
2. Type CONNECT kdilks and press Enter
3. Type oracle1 and press Enter
4. Type SET SERVEROUTPUT ON and press Enter
5. Type EXEC dbms_output.put_line(sys_context('emp_user', 'id')); and press Enter
6. Type EXEC dbms_output.put_line(sys_context('emp_user', 'name')); and press Enter
7. Type EXEC dbms_output.put_line(sys_context('emp_user', 'email')); and press Enter

Task 5: Viewing context information


Execute the lab_11_01_06.sql script using the @ command to connect as user KDILKS
and list the application context attributes set in the current session. Then log in as the
SEC user with a password of "oracle_1." Select the application context EMP_USER from
the DBA_CONTEXT data dictionary view. Include the FROM and WHERE clauses on
separate lines.

Steps list
Instructions
1. Type @lab_11_01_06.sql and press Enter
2. Type CONNECT sec and press Enter
3. Type oracle_1 and press Enter
4. Type SELECT * and press Enter

Steps list
Instructions
5. Type FROM dba_context and press Enter
6. Type WHERE namespace = 'EMP_USER'; and press Enter

Potrebbero piacerti anche