webworm
webworm

Reputation: 11019

Using windows authentication for database connection - Which user is used?

I have am ASP.NET Web API application that currently makes use of SQL Authentication when connecting to the database. I would like to change the connection to using Windows Authentication. In doing so, how do I specify the user that the web app, and therefore the database access, makes use of? I am using IIS v8.5.9600.16384

Upvotes: 0

Views: 1247

Answers (2)

T McKeown
T McKeown

Reputation: 12847

I can't say I agree with using integrated for the applications DB access as it makes security a bit more challenging as well as the coding issues tied to always having to deal with the possibility of different priv's for each user but obviously I don't know all the requirements of your situation.

So to answer your question:

  • If your connection string is set to Intergated Security the identity of the executing thread is used to provide the credentials.

  • By default the identity of the ASP.NET Worker Process will be the network credentials tied to the identity.

  • You can view the credentials like this:

    IPrincipal threadPrincipal = Thread.CurrentPrincipal;
    Console.WriteLine("Name: {0}\nIsAuthenticated: {1}" +
        "\nAuthenticationType: {2}", 
        threadPrincipal.Identity.Name, 
        threadPrincipal.Identity.IsAuthenticated,
        threadPrincipal.Identity.AuthenticationType);
    

You may set the identity via impersonation in the web.config or programatically.

Web.config:

<identity impersonate="true" userName="accountname" password="password" />

Code: (using the creds of the HttpContext user) this assumes that IIS is using integrated too

System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext = 
((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();

//User is the HttpContext.User
//Insert your code that runs under the security context of the authenticating user here.

impersonationContext.Undo();  

Upvotes: 2

Mikee
Mikee

Reputation: 1651

You will have to turn off Anonymous Authentication and enable Windows Authentication via IIS Manager.

Upvotes: 0

Related Questions