Welcome to EMC Consulting Blogs Sign in | Join | Help

Christian Wade's Blog

SQL-CLR: WindowsIdentity.Impersonate()

There is some literature out there that says it is possible to impersonate the current user’s logon for external access (file system, registry, etc.) in SQL/CLR sprocs, but not much in the way of sample code.  As I have crossed this bridge, I thought I should share the knowledge.  This now works with assemblies catalogued as EXTERNAL_ACCESS.  I think in previous betas, it would only work on UNSAFE assemblies.

// Use current user's context to access external resource - unless

// logged in using SQL authentication where WindowsIdentity will

where WindowsIdentity will

// be null and will use SQL Server service account


WindowsImpersonationContext newContext = null;
WindowsIdentity newIdentity = SqlContext
.WindowsIdentity;

try
{
   if (newIdentity != null) newContext = newIdentity.Impersonate();

   // do external access here
}
catch
{
   
// ...
}
finally
{
   if (newContext != null) newContext.Undo();
}


Note


EXECUTE
AS LOGIN = 'login1' allows impersonation of a login from TSQL.

The WITH EXECUTE AS clause of stored procedure declarations allows the execution context to revert to a context other than the default of CALLER in the event that the object-ownership chain is broken (e.g. dynamic SQL). For example, it could revert to the context of the stored procedure owner.

These options have no effect on impersonation outside SQL Server.

Published 05 May 2005 14:34 by christian.wade

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server (Personal Edition), by Telligent Systems