sp_setapprole (Transact-SQL)
Activates the permissions associated with an application role in the current database.
After an application role is activated by using sp_setapprole, the role remains active until the user either disconnects from the server or executes sp_unsetapprole. sp_setapprole can be executed only by direct Transact-SQL statements. sp_setapprole cannot be executed within another stored procedure or within a user-defined transaction.
For an overview of application roles, see Application Roles.
Security Note |
|---|
To protect the application role password when it is transmitted across a network, you should always use an encrypted connection when enabling an application role.. The Microsoft ODBC encrypt option is not supported by SqlClient. If you must store credentials, encrypt them with the crypto API functions. The parameter password is stored as a one-way hash. To preserve compatibility with earlier versions of SQL Server, password complexity policy is not enforced by sp_addapprole. To enforce password complexity policy, use CREATE APPLICATION ROLE. |
A. Activating an application role without the encrypt option
The following example activates an application role named SalesAppRole, with the plain-text password AsDeF00MbXX, created with permissions specifically designed for the application used by the current user.
EXEC sp_setapprole 'SalesApprole', 'AsDeF00MbXX'; GO
B. Activating an application role with a cookie and then reverting to the original context
The following example activates the Sales11 application role with password fdsd896#gfdbfdkjgh700mM, and creates a cookie. The example returns the name of the current user, and then reverts to the original context by executing sp_unsetapprole.
DECLARE @cookie varbinary(8000);
EXEC sp_setapprole 'Sales11', 'fdsd896#gfdbfdkjgh700mM'
, @fCreateCookie = true, @cookie = @cookie OUTPUT;
-- The application role is now active.
SELECT USER_NAME();
-- This will return the name of the application role, Sales11.
EXEC sp_unsetapprole @cookie;
-- The application role is no longer active.
-- The original context has now been restored.
GO
SELECT USER_NAME();
-- This will return the name of the original user.
GO