Search code examples
sqlsql-server-2008-r2database-restoredatabase-permissions

Sql Server grant permission for sp_grantdbaccess on a newly restored DB


I am unable to grant access to a newly restored database using sp_grantdbaccess. I am trying to do this via dynamic sql like below.

DECLARE @grant_access nvarchar(500)
SET @grant_access = 'EXEC ' + @new_db_name + '.dbo.sp_grantdbaccess ''IIS APPPOOL\myApp'''
EXEC sp_executesql @grant_access

I get the below error back trying to run this from a sproc. Any ideas on how I can grant permission for the app to call sp_grantdbaccess etc? I guess I am needing permission to give permission...

Error restore_backup restore_new_configDBThe server principal "IIS APPPOOL\myApp" is not able to access the database "new_db_name" under the current security context


Solution

  • Based on the error message it looks like you are trying to grant access to IIS APPPOOL\myApp using the security context IIS APPPOOL\myApp, but IIS APPPOOL\myApp doesn't have the access rights to the db to grant access rights to itself. I think this is akin to me trying to grant myself access to my neighbors house, but I don't have any authority to do so.

    Depending on what type of security policies you are working under, I would either run the app pool under an account that has the greater privileges through integrated auth (but this might negate your need to grant privileges), or execute these SQL statements using a local SQL account with the necessary privileges to the database. In these cases, it would be like asking my neighbor (elevated access) to let me (IIS APPPOOL\myApp) in.

    If you think it should work because IIS APPPOOL\myApp had access to the DB prior to being backed up, could this be a problem with IIS APPPOOL\myApp being an orphaned user? See http://msdn.microsoft.com/en-us/library/ms175475.aspx But with this case, you still might run into the above scenario trying to fix the orphaned user.