Establishing an explicit trusted connection and switching the user ID
You can establish an explicit trusted connection by making a request within an application when a connection to a Db2® database is established. The security administrator must have previously defined a trusted context, using the CREATE TRUSTED CONTEXT statement, with attributes matching those of the connection you are establishing (see Step 1, later).
Before you begin
The API you use to request an explicit trusted connection when you establish a connection depends on the type of application you are using (see the table in Step 2).
After you have established an explicit trusted connection, the application can switch the user ID of the connection to a different user ID using the appropriate API for the type of application (see the table in Step 3).
Procedure
Example of establishing an explicit trusted connection and switching the user
In the following example, a middle-tier server needs to issue some database requests on behalf of an end-user, but does not have access to the end-user's credentials to establish a database connection on behalf of that end-user.
int main(int argc, char *argv[])
{
SQLHANDLE henv; /* environment handle */
SQLHANDLE hdbc1; /* connection handle */
char origUserid[10] = "newton";
char password[10] = "test";
char switchUserid[10] = "zurbie";
char dbName[10] = "testdb";
// Allocate the handles
SQLAllocHandle( SQL_HANDLE_ENV, &henv );
SQLAllocHandle( SQL_HANDLE_DBC, &hdbc1 );
// Set the trusted connection attribute
SQLSetConnectAttr( hdbc1, SQL_ATTR_USE_TRUSTED_CONTEXT,
SQL_TRUE, SQL_IS_INTEGER );
// Establish a trusted connection
SQLConnect( hdbc1, dbName, SQL_NTS, origUserid, SQL_NTS,
password, SQL_NTS );
//Perform some work under user ID "newton"
. . . . . . . . . . .
// Commit the work
SQLEndTran(SQL_HANDLE_DBC, hdbc1, SQL_COMMIT);
// Switch the user ID on the trusted connection
SQLSetConnectAttr( hdbc1,
SQL_ATTR_TRUSTED_CONTEXT_USERID, switchUserid,
SQL_IS_POINTER
);
//Perform new work using user ID "zurbie"
. . . . . . . . .
//Commit the work
SQLEndTranSQL_HANDLE_DBC, hdbc1, SQL_COMMIT);
// Disconnect from database
SQLDisconnect( hdbc1 );
return 0;
} /* end of main */
What to do next
- When does the user ID actually get switched?
- After the command to switch the user on the trusted connection
is issued, the switch user request is not performed until the next
statement is sent to the server. This is demonstrated by the following
example where the list applications command shows
the original user ID until the next statement is issued.
- Establish an explicit trusted connection with USERID1.
- Issue the switch user command, such as getDB2Connection for USERID2.
- Run
db2 list applications
. It still shows that USERID1 is connected. - Issue a statement on the trusted connection, such as
executeQuery("values current sqlid")
, to perform the switch user request at the server. - Run
db2 list applications
again. It now shows that USERID2 is connected.