Experience: is what you get soon after you need it.

Experience: is what you get soon after you need it.

Rasul Allah (sal Allahu alaihi wa sallam) said: "Restore the trusts of those who trust you, and deal not falsely with him who deals falsely with you." [Abu Dawud, Tirmidhi]

Search This Blog

Monday, September 28, 2015

Create and manage contexts

Create and manage contexts

What is an Application Context?

An application context is a set of name-value pairs that Oracle Database stores in memory. The application context has a label called a namespace, for example, empno_ctx for an application context that retrieves employee IDs. Inside the context are the name-value pairs (an associative array): the name points to a location in memory that holds the value. An application can use the application context to access session information about a user, such as the user ID or other user-specific information, or a client ID, and then securely pass this data to the database. You can then use this information to either permit or prevent the user from accessing data through the application. You can use application contexts to authenticate both database and nondatabase users


The components of the name-value pair are as follows:
  • Name. Refers to the name of the attribute set that is associated with the value. For example, if the empno_ctx application context retrieves an employee ID from the HR.EMPLOYEES table, it could have a name such as employee_id.
  • Value. Refers to a value set by the attribute. For example, for the empno_ctx application context, if you wanted to retrieve an employee ID from the HR.EMPLOYEES table, you could create a value called emp_id that sets the value for this ID.

Oracle Database stores the application context values in a secure data cache available in the User Global Area (UGA) or the System (sometimes called "Shared") Global Area (SGA)

Types of Application Contexts

There are three general categories of application contexts:
  • Database session-based application contexts. This type retrieves data that is stored in the database user session (that is, the UGA) cache. There are three categories of database session-based application contexts:
    • Initialized locally. Initializes the application context locally, to the session of the user.
    • Initialized externally. Initializes the application context from an Oracle Call Interface (OCI) application, a job queue process, or a connected user database link.
    • Initialized globally. Uses attributes and values from a centralized location, such as an LDAP directory.
  • Global application contexts. This type retrieves data that is stored in the System Global Area (SGA) so that it can be used for applications that use a sessionless model, such as middle-tier applications in a three-tiered architecture. A global application context is useful if the session context must be shared across sessions, for example, through connection pool implementations.
  • Client session-based application contexts. This type uses Oracle Call Interface functions on the client side to set the user session data, and then to perform the necessary security checks to restrict user access.

Database Session-Based Application Contexts

If you must retrieve session information for database users, use a database session-based application context. This type of application context uses a PL/SQL procedure within Oracle Database to retrieve, set, and secure the data it manages


The database session-based application context is managed entirely within Oracle Database. Oracle Database sets the values, and then when the user exits the session, automatically clears the application context values stored in cache. If the user connection ends abnormally, for example, during a power failure, then the PMON background process cleans up the application context data.You do not need to explicitly clear the application context from cache.

Retrieve session information. To retrieve the user session information, you can use the SYS_CONTEXT SQL function. The SYS_CONTEXT function returns the value of the parameter associated with the context namespace. You can use this function in both SQL and PL/SQL statements. Typically, you will use the built-in USERENV namespace to retrieve the session information of a user.

Set the name-value attributes of the application context you created with CREATE CONTEXT. You can use the DBMS_SESSION.SET_CONTEXT procedure to set the name-value attributes of the application context. The name-value attributes can hold information such as the user ID, IP address, authentication mode, the name of the application, and so on. The values of the attributes you set remain either until you reset them, or until the user ends the session. Note the following:
  • If the value of the parameter in the namespace already has been set, then SET_CONTEXT overwrites this value.
  • Be aware that any changes in the context value are reflected immediately and subsequent calls to access the value through the SYS_CONTEXT function will return the most recent value


Be executed by users. After you create the package, the user will need to execute the package when he or she logs on. You can create a logon trigger to execute the package automatically when the user logs on, or you can embed this functionality in your applications. Remember that the application context session values are cleared automatically when the user ends the session, so you do not need to manually remove the session data.


Using SYS_CONTEXT with Database Links

When SQL statements within a user session involve database links, then Oracle Database runs the SYS_CONTEXT SQL function at the host computer of the database link, and then captures the context information there (at the host computer).

If remote PL/SQL procedure calls are run on a database link, then Oracle Database runs any SYS_CONTEXT function inside such a procedure at the destination database of the link. In this case, only externally initialized application contexts are available at the database link destination site. For security reasons, Oracle Database propagates only the externally initialized application context information to the destination site from the initiating database link site

Using DBMS_SESSION.SET_CONTEXT to Set Session Information

DBMS_SESSION.SET_CONTEXT (
  namespace VARCHAR2,
  attribute VARCHAR2,
  value     VARCHAR2,
  username  VARCHAR2,
  client_id VARCHAR2);


Demo:
SHAIKDB>select * from dba_context where schema='LOB';

NAMESPACE              SCHEMA                 PACKAGE                TYPE
------------------------------ ------------------------------ ------------------------------ ----------------------
EMP                  LOB                 EMP_PKG                ACCESSED LOCALLY

SHAIKDB>show user
USER is "LOB"

SHAIKDB>drop context emp;

Context dropped.


SHAIKDB>create context emp using emp_pkg;

Context created.

SHAIKDB>create package emp_pkg is
   procedure emp_proc;
   end;
   /

Package created.

SHAIKDB>create or replace package body emp_pkg is
procedure emp_proc is
  id hr.employees.employee_id%type;
 lname hr.employees.last_name%type;
 income hr.employees.salary%type;
 social hr.employees.ssn%type;
begin
select employee_id,last_name,salary,ssn into id,lname,income,social from
hr.employees where first_name=sys_context('USERENV','SESSION_USER');
dbms_session.set_context('emp','employee_id',id);
dbms_session.set_context('emp','fist_name',sys_context('USERENV','SESSION_USER'));
dbms_session.set_context('emp','last_name',lname);
dbms_session.set_context('emp','salary',income);
dbms_session.set_context('emp','ssn',social);
exception
when no_data_found then null;
end;
end;
/
Package body created.


Insert data into the hr table for user LOB & PFAY:

SHAIKDB>/
Enter value for id: 223
Enter value for fname: LOB
Enter value for lname: LOB
Enter value for name: LOB
Enter value for phone: 5141234567
old   1: insert into hr.employees values (&id,'&fname','&lname','&NAME','&phone',sysdate,'AD_VP',50000,null,null,100,null)
new   1: insert into hr.employees values (223,'LOB','LOB','LOB','5141234567',sysdate,'AD_VP',50000,null,null,100,null)

1 row created.

SHAIKDB>create trigger log_trigger after logon on database
    begin
      lob.emp_pkg.emp_proc;
     end;
   /

Trigger created.



[oracle@collabn1 ~]$ sqlplus pfay/pfay

SQL*Plus: Release 11.2.0.1.0 Production on Mon Sep 28 19:50:08 2015

Copyright (c) 1982, 2009, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, Real Application Clusters, OLAP, Data Mining
and Real Application Testing options

SHAIKDB>select sys_context('USERENV','SESSION_USER') from dual;

SYS_CONTEXT('USERENV','SESSION_USER')
----------------------------------------------------------------------------------------------------
PFAY


SHAIKDB>select sys_context('emp','employee_id') from dual;

SYS_CONTEXT('EMP','EMPLOYEE_ID')
----------------------------------------------------------------------------------------------------
222


SHAIKDB>select sys_context('emp','first_name') from dual;

SYS_CONTEXT('EMP','FIRST_NAME')
----------------------------------------------------------------------------------------------------
PFAY

SHAIKDB>select sys_context('emp','last_name') from dual;

SYS_CONTEXT('EMP','LAST_NAME')
----------------------------------------------------------------------------------------------------
PFAY_LAST

SHAIKDB>select sys_context('emp','salary') from dual;

SYS_CONTEXT('EMP','SALARY')
----------------------------------------------------------------------------------------------------
50000

SHAIKDB>select sys_context('emp','ssn') from dual;

SYS_CONTEXT('EMP','SSN')
----------------------------------------------------------------------------------------------------




SHAIKDB>select sys_context('USERENV','SESSION_USER') from dual;

SYS_CONTEXT('USERENV','SESSION_USER')
----------------------------------------------------------------------------------------------------
LOB



Let’s create a trigger to test the context values:




Demo2:
You cannot set the context manually it has to set via package:

SHAIKDB>grant create trigger,create procedure,create any context,create session to pfay;

Grant succeeded.

SHAIKDB>exec dbms_session.set_context('emp1','id',1000);
BEGIN dbms_session.set_context('emp1','id',1000); END;

*
ERROR at line 1:
ORA-01031: insufficient privileges
ORA-06512: at "SYS.DBMS_SESSION", line 101
ORA-06512: at line 1




SHAIKDB>create context test1 using test_pkg;

Context created.

SHAIKDB>create package test_pkg is
 2  procedure test_proc;
 3  end;
 4  /

Package created.

SHAIKDB>create or replace package body test_pkg is
 2  procedure test_proc is
 3  begin
 4  dbms_session.set_context('test1','id',1000);
 5  end;
 6  end;
 7  /

Package body created.

SHAIKDB>create trigger test1_trigger after logon on schema
 2  begin
 3  pfay.test_pkg.test_proc;
 4  end;
 5  /

Trigger created.


Predefined Parameters of Namespace USERENV

Parameter
Return Value
ACTION
Identifies the position in the module (application name) and is set through the DBMS_APPLICATION_INFO package or OCI.
AUDITED_CURSORID
Returns the cursor ID of the SQL that triggered the audit. This parameter is not valid in a fine-grained auditing environment. If you specify it in such an environment, then Oracle Database always returns NULL.
AUTHENTICATED_IDENTITY
Returns the identity used in authentication. In the list that follows, the type of user is followed by the value returned:
Kerberos-authenticated enterprise user: kerberos principal name Kerberos-authenticated external user : kerberos principal name; same as the schema name SSL-authenticated enterprise user: the DN in the user's PKI certificate SSL-authenticated external user: the DN in the user's PKI certificate Password-authenticated enterprise user: nickname; same as the login name Password-authenticated database user: the database username; same as the schema name OS-authenticated external user: the external operating system user name Radius/DCE-authenticated external user: the schema name Proxy with DN : Oracle Internet Directory DN of the client Proxy with certificate: certificate DN of the client Proxy with username: database user name if client is a local database user; nickname if client is an enterprise user. SYSDBA/SYSOPER using Password File: login name SYSDBA/SYSOPER using OS authentication: operating system user name
AUTHENTICATION_DATA
Data being used to authenticate the login user. For X.503 certificate authenticated sessions, this field returns the context of the certificate in HEX2 format.
Note: You can change the return value of the AUTHENTICATION_DATA attribute using the length parameter of the syntax. Values of up to 4000 are accepted. This is the only attribute of USERENV for which Oracle Database implements such a change.
AUTHENTICATION_METHOD
Returns the method of authentication. In the list that follows, the type of user is followed by the method returned:
Password-authenticated enterprise user, local database user, or SYSDBA/SYSOPER using Password File; proxy with username using password: PASSWORD Kerberos-authenticated enterprise or external user: KERBEROS SSL-authenticated enterprise or external user: SSL Radius-authenticated external user: RADIUS OS-authenticated external user or SYSDBA/SYSOPER: OS DCE-authenticated external user: DCE Proxy with certificate, DN, or username without using password: NONE Background process (job queue slave process): JOB You can use IDENTIFICATION_TYPE to distinguish between external and enterprise users when the authentication method is Password, Kerberos, or SSL.
BG_JOB_ID
Job ID of the current session if it was established by an Oracle Database background process. Null if the session was not established by a background process.
CLIENT_IDENTIFIER
Returns an identifier that is set by the application through the DBMS_SESSION.SET_IDENTIFIER procedure, the OCI attribute OCI_ATTR_CLIENT_IDENTIFIER, or the Java class Oracle.jdbc.OracleConnection.setClientIdentifier. This attribute is used by various database components to identify lightweight application users who authenticate as the same database user.
CLIENT_INFO
Returns up to 64 bytes of user session information that can be stored by an application using the DBMS_APPLICATION_INFO package.
CURRENT_BIND
The bind variables for fine-grained auditing.
CURRENT_EDITION_ID
The identifier of the current edition.
CURRENT_EDITION_NAME
The name of the current edition.
CURRENT_SCHEMA
The name of the currently active default schema. This value may change during the duration of a session through use of an ALTER SESSION SET CURRENT_SCHEMA statement. This may also change during the duration of a session to reflect the owner of any active definer's rights object. When used directly in the body of a view definition, this returns the default schema used when executing the cursor that is using the view; it does not respect views used in the cursor as being definer's rights.
Note: Oracle recommends against issuing the SQL statement ALTER SESSION SET CURRENT_SCHEMA from within a stored PL/SQL unit.
CURRENT_SCHEMAID
Identifier of the currently active default schema.
CURRENT_SQL
CURRENT_SQLn
CURRENT_SQL returns the first 4K bytes of the current SQL that triggered the fine-grained auditing event. The CURRENT_SQLn attributes return subsequent 4K-byte increments, where n can be an integer from 1 to 7, inclusive. CURRENT_SQL1 returns bytes 4K to 8K; CURRENT_SQL2 returns bytes 8K to 12K, and so forth. You can specify these attributes only inside the event handler for the fine-grained auditing feature.
CURRENT_SQL_LENGTH
The length of the current SQL statement that triggers fine-grained audit or row-level security (RLS) policy functions or event handlers. Valid only inside the function or event handler.
CURRENT_USER
The name of the database user whose privileges are currently active. This may change during the duration of a session to reflect the owner of any active definer's rights object. When no definer's rights object is active, CURRENT_USER returns the same value as SESSION_USER. When used directly in the body of a view definition, this returns the user that is executing the cursor that is using the view; it does not respect views used in the cursor as being definer's rights.
CURRENT_USERID
The identifier of the database user whose privileges are currently active.
DATABASE_ROLE
The database role using the SYS_CONTEXT function with the USERENV namespace. The role is one of the following: PRIMARY, PHYSICAL STANDBY, LOGICAL STANDBY, SNAPSHOT STANDBY.
DB_DOMAIN
Domain of the database as specified in the DB_DOMAIN initialization parameter.
DB_NAME
Name of the database as specified in the DB_NAME initialization parameter.
DB_UNIQUE_NAME
Name of the database as specified in the DB_UNIQUE_NAME initialization parameter.
ENTRYID
The current audit entry number. The audit entryid sequence is shared between fine-grained audit records and regular audit records. You cannot use this attribute in distributed SQL statements. The correct auditing entry identifier can be seen only through an audit handler for standard or fine-grained audit.
ENTERPRISE_IDENTITY
Returns the user's enterprise-wide identity:
For enterprise users: the Oracle Internet Directory DN. For external users: the external identity (Kerberos principal name, Radius and DCE schema names, OS user name, Certificate DN). For local users and SYSDBA/SYSOPER logins: NULL. The value of the attribute differs by proxy method:
For a proxy with DN: the Oracle Internet Directory DN of the client For a proxy with certificate: the certificate DN of the client for external users; the Oracle Internet Directory DN for global users For a proxy with username: the Oracle Internet Directory DN if the client is an enterprise users; NULL if the client is a local database user.
FG_JOB_ID
Job ID of the current session if it was established by a client foreground process. Null if the session was not established by a foreground process.
GLOBAL_CONTEXT_MEMORY
Returns the number being used in the System Global Area by the globally accessed context.
GLOBAL_UID
Returns the global user ID from Oracle Internet Directory for Enterprise User Security (EUS) logins; returns null for all other logins.
HOST
Name of the host machine from which the client has connected.
IDENTIFICATION_TYPE
Returns the way the user's schema was created in the database. Specifically, it reflects the IDENTIFIED clause in the CREATE/ALTER USER syntax. In the list that follows, the syntax used during schema creation is followed by the identification type returned:
IDENTIFIED BY password: LOCAL IDENTIFIED EXTERNALLY: EXTERNAL IDENTIFIED GLOBALLY: GLOBAL SHARED IDENTIFIED GLOBALLY AS DN: GLOBAL PRIVATE
INSTANCE
The instance identification number of the current instance.
INSTANCE_NAME
The name of the instance.
IP_ADDRESS
IP address of the machine from which the client is connected. If the client and server are on the same machine and the connection uses IPv6 addressing, then ::1 is returned.
ISDBA
Returns TRUE if the user has been authenticated as having DBA privileges either through the operating system or through a password file.
LANG
The abbreviated name for the language, a shorter form than the existing 'LANGUAGE' parameter.
LANGUAGE
The language and territory currently used by your session, along with the database character set, in this form:
language_territory.characterset
MODULE
The application name (module) set through the DBMS_APPLICATION_INFO package or OCI.
NETWORK_PROTOCOL
Network protocol being used for communication, as specified in the 'PROTOCOL=protocol' portion of the connect string.
NLS_CALENDAR
The current calendar of the current session.
NLS_CURRENCY
The currency of the current session.
NLS_DATE_FORMAT
The date format for the session.
NLS_DATE_LANGUAGE
The language used for expressing dates.
NLS_SORT
BINARY or the linguistic sort basis.
NLS_TERRITORY
The territory of the current session.
OS_USER
Operating system user name of the client process that initiated the database session.
POLICY_INVOKER
The invoker of row-level security (RLS) policy functions.
PROXY_ENTERPRISE_IDENTITY
Returns the Oracle Internet Directory DN when the proxy user is an enterprise user.
PROXY_GLOBAL_UID
Returns the global user ID from Oracle Internet Directory for Enterprise User Security (EUS) proxy users; returns NULL for all other proxy users.
PROXY_USER
Name of the database user who opened the current session on behalf of SESSION_USER.
PROXY_USERID
Identifier of the database user who opened the current session on behalf of SESSION_USER.
SERVER_HOST
The host name of the machine on which the instance is running.
SERVICE_NAME
The name of the service to which a given session is connected.
SESSION_EDITION_ID
The identifier of the session edition.
SESSION_EDITION_NAME
The name of the session edition.
SESSION_USER
The name of the database user at logon. For enterprise users, returns the schema. For other users, returns the database user name. This value remains the same throughout the duration of the session.
SESSION_USERID
The identifier of the database user at logon.
SESSIONID
The auditing session identifier. You cannot use this attribute in distributed SQL statements.
SID
The session ID.
STATEMENTID
The auditing statement identifier. STATEMENTID represents the number of SQL statements audited in a given session. You cannot use this attribute in distributed SQL statements. The correct auditing statement identifier can be seen only through an audit handler for standard or fine-grained audit.
TERMINAL
The operating system identifier for the client of the current session. In distributed SQL statements, this attribute returns the identifier for your local session. In a distributed environment, this is supported only for remote SELECT statements, not for remote INSERT, UPDATE, or DELETE operations. (The return length of this parameter may vary by operating system.)



Data Dictionary Views That Display Information about Application Contexts

View
Description
ALL_CONTEXT
Describes all context namespaces in the current session for which attributes and values were specified using the DBMS_SESSION.SET_CONTEXT procedure. It lists the namespace and its associated schema and PL/SQL package.
ALL_POLICY_CONTEXTS
Describes the driving contexts defined for the synonyms, tables, and views accessible to the current user. (A driving context is a context used in a Virtual Private Database policy.)
DBA_CONTEXT
Provides all context namespace information in the database. Its columns are the same as those in the ALL_CONTEXT view, except that it includes the TYPE column. The TYPE column describes how the application context is accessed or initialized.
DBA_POLICY_CONTEXTS
Describes all driving contexts in the database that were added by the DBMS_RLS.ADD_POLICY_CONTEXT procedure. Its columns are the same as those in ALL_POLICY_CONTEXTS.
SESSION_CONTEXT
Describes the context attributes and their values set for the current session.
USER_POLICY_CONTEXTS
Describes the driving contexts defined for the synonyms, tables, and views owned by the current user. Its columns (except for OBJECT_OWNER) are the same as those in ALL_POLICY_CONTEXTS.
V$CONTEXT
Lists set attributes in the current session. Users do not have access to this view unless you grant the user the SELECT privilege on it.
V$SESSION
Lists detailed information about each current session. Users do not have access to this view unless you grant the user the SELECT privilege on it


Documentation:
Oracle® Database Security Guide 11g Release 2 (11.2) → Part Number E10574-02 → 6 Using Application Contexts to Retrieve User Information

SYS_CONTEXT → Oracle® Database SQL Language Reference 11g Release 2 (11.2) → Part Number E10592-02

No comments: