3

So we have our web app up and going with entity framework. What we'd like to do is impersonate the current user when we're accessing the DB. We're not interested in setting impersonation up in our web config.

Ideally using something like this: Link when we're about to access data.

UPDATED: I'm looking for a way to abstract this code out so I don't have to have it in every repository function call.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
RailRhoad
  • 2,128
  • 2
  • 25
  • 39

1 Answers1

4

Your EF connection string is going to need to be set up for using a trusted connection.

You won't need to set up Impersonation in your web.config, but you do need to be using Windows Authentication.

Then just do this:

using (((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate())
using (var dbContext = new MyEntityFrameworkContainer())
{
    ...
}

Any code inside the curly braces of the using statements will run as the authenticated user.

Bryan Batchelder
  • 3,627
  • 21
  • 17
  • 1
    Ok, that's similar to the link I posted but I'm looking for a way to abstract that out into an EF event (or somewhere) where I don't have to keep declaring that in every repository function. – RailRhoad Dec 23 '09 at 20:05
  • Probably not the best idea. What happens when you want to perform a query under the system identity? I would definitely keep impersonation opt-in rather than opt-out. – Bryan Batchelder Dec 29 '09 at 01:25
  • I wonder if this works with the new Active Directory Integrated Authentication for Azure SQL Database. Actually what I'd like to do is impersonate a SQL Server Authentication login. – CalvinDale May 04 '17 at 18:01
  • Can someone explain why we build a new context within the impersonation using statement? – James Aug 08 '17 at 15:30