Libin TK
Libin TK

Reputation: 1497

Entity Framework Windows Authentication with ASP.NET Impersonation

I have an ASP.NET application which uses Impersonation. My ConnectionStrings are dynamically generated using EntityConnectionStringBuilder.

It works fine when I am using SQL Server Authentication but when I use Windows Authentication by replace User Id and Password with Trusted_Connection=Yes; I am getting an error saying "System.Data.SqlClient.SqlException (0x80131904): Cannot open database "DB_Name" requested by the login. The login failed. Login failed for user 'DomainName\MachineName$'".

It looks like Entity Framework is using an inbuilt User Account (MachineName$) instead of the Impersonated user 'DomainName\User1'.

How to configure EF to use the Impersonated User Account for Windows Authentication?

Upvotes: 0

Views: 5186

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

You aren't using impersonation. If you were, then this would be working (assuming your database were otherwise correctly configured to allow access from the impersonated user).

EF is not using a "built-in" account. It's using whatever account the worker process is running under, which in most cases will be either an Application Pool identity, or Network Service, both of which use the machines Active Directory account for credentials.

In other words, EF uses whatever the connection string tells it to use, and if you're telling it to use a trusted connection, then it uses whatever the process/thread is running under.

In point of fact, impersonation is not supported in IIS7 or greater when running in Integrated pipeline mode. The reason for this is that IIS7 is more strongly tied to .NET and supports asynchronous handlers. Asynch handlers have issues with impersonation because the thread that started the handler, may not be the same thread that resumes the handler when the async request resumes after giving up its thread to do the async work.

In general, unless you have a very specific use case, you probably should not design your architecture to require impersonation, as this has a lot of repercussions.

If you need to utilize a resource with a specific user, then you can use a WindowsIdentity principal and Impersonate that way, but this has to be done in the confines of a small block (the network call itself).

I'm not sure how you are trying to do impersonation, but it's obviously not working. In most cases, you should be getting an error if you try to impersonate on IIS7+, so the question really is... What makes you think you're using impersonation?

Upvotes: 2

Related Questions