You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Running a published aspnet core app with windows auth and Trusted_Connection connectionString #1805
Hi there,
What is the best practice for configuring an enterprise asp.net core app which uses windows active directory auth - specifically in relation to DB connectionStrings? What I was hoping for is to use Trusted_Connection (e.g. Server=XXX;Database=YYY;Trusted_Connection=true;) and to configure IIS / dotnet to run the core app using windows user impersonation (or whatever it's called) so that the core app would issue DB queries using the credentials of the user who is browsing the web app.
The core process appears to inherit the user credentials of the IIS website user (as configured in IISM > app pool & site) - which in fairness is in keeping with how IIS apps used to run. So Trusted_Connection doesn't work for application user (pass through auth) so I either have to make the IIS site run as a specific windows user or use sql user auth in the connection string (e.g. Server=XXX;Database=YYY;User ID=myUsername;Password=myPassword;)
Is there a way to do Trusted_Connection as the user browsing the website?
Ok it's not quite working - but I expect there's something I've done wrong. If I browse the website on the server (i.e. within a remote desktop session) then it works but not when I browse from another computer (SqlException: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.).
I'll look into it further tomorrow - think its the same bug you mentioned in one of the other threads. I'm using .net 4.5.1 btw - I see you had a solution for 4.6.
Code:
using ((User.Identity as WindowsIdentity).Impersonate())
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
using (var reader = command.ExecuteReader())
{
@divega From the issue and the repro code, the issue is related to .Net Framework 4.6.1 @ilanc project.json content "frameworks": { "net461": { } },
For .Net core on Windows, the WindowsIdentity.GetCurrent() API is used to retrieve the user connecting to the DataBase. If the impersonation was successful, the SqlClient should be able to get the correct user to login to the DB.
@ilanc I am running the application using dotnet run
It runs successfully on localhost:5000
I don't see any authentication request. How do I get the authentication to ask for credentials?
@ilanc I hosted this app in IIS and enable authentication the way you have instructed above.
I visited the URL on the localhost
From a different machine
I also tried this from @corivera 's machine. I got an error message stating that the authentication for corivera failed.
Then I added corivera to the users on the SqlServer and the authentication went through and I could see the data from the server.
(I don't have screenshots for this)
For Net Framework 461 the Impersonation seems to be working right.
Let me know if I missed out any steps or if you have any other questions/instructions.
I'm not sure but is "aspnet core app with windows auth and Trusted_Connection connectionString" running now with ASP.NET Core 2.0 or not?
I use a ASP.NET Core 2.0 (targeting NET 4.6.1) and the following Code (Middleware) to have the current user logon to sqlserver but always the 'NT AUTHORITY\ANONYMOUS LOGON' connects to the sqlserver...
public class Impersonate
{
private readonly RequestDelegate next;
public Impersonate(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
var winIdent = context.User.Identity as WindowsIdentity;
if (winIdent == null)
{
await next.Invoke(context);
}
else
{
await WindowsIdentity.RunImpersonated(winIdent.AccessToken, async () =>
{
await next.Invoke(context);
});
}
}
}
Please help - I need to have the current user connect to sqlserver...
Hi, after some investigation the code in my last post works (app.UseMiddleware();)
It was necessary to set the SPN on the Domain Controller for the Webserver like:
setspn -a HTTP/web webserver
setspn -a HTTP/web fully qualified webserver
ie.
setspn -a HTTP/Test testwebserver
setspn -a HTTP/Test.domain1.intern testwebserver
and in IIS only Windows Authentication with Negotiate and NTLM...
ASYNC IMPERSONATION IS A TRAP. It will only work if your application pipeline runs synchronously. I'm going to start removing comments / samples that propose it so others don't make the same mistake.
Impersonation should only be done at the call site where it's required, and that action must be completed synchronously within the RunImpersonated call.
Does this mean it is not possible to make a database call "async" like this?
public async Task<ActionResult> Read(int mitgliedid, string textfilter, [DataSourceRequest]DataSourceRequest request)
{
var callerIdentity = User.Identity as WindowsIdentity;
WindowsIdentity.RunImpersonated(callerIdentity.AccessToken, () =>
{
IList<MitgliedkontaktViewModel> result = await Db.QueryAsync<MitgliedkontaktViewModel>("SELECT_Mitgliedkontakt", new { Mitglied_ID = mitgliedid }, commandType: System.Data.CommandType.StoredProcedure);
return Json(await result.ToDataSourceResultAsync(request));
});
}
there are so many posts which make it not clear how to use it the right way...
in my application it is important that every database call is made by the current logged on user, so it would be nice if Microsoft can clarify, how to do this in an ASP.NET MVC Core 2 Applicatuion the right way!
Correct, async operations cannot be combine with impersonation.
@divega accessing the DB as the authenticated user is the most requested use of impersonation. Does EF have other ways to control the authentication process? Or other recommendations for authorizing individual user access to the database?
it is only possible to use impersonation in Sync Actions?
I have to add the code for impersonation in every action where I want to make a database call?
if this is true, this is a great disadvantage of ASP.NET Core and contradict with the Middleware logic of ASP.NET Core - isn't it (so many repeated code)?
so this Action should work?
public IActionResult Read(int mitgliedid, string textfilter, [DataSourceRequest]DataSourceRequest request)
{
var callerIdentity = User.Identity as WindowsIdentity;
WindowsIdentity.RunImpersonated(callerIdentity.AccessToken, () =>
{
IList<MitgliedkontaktViewModel> result = Db.Query<MitgliedkontaktViewModel>("SELECT_Mitgliedkontakt", new { Mitglied_ID = mitgliedid }, commandType: System.Data.CommandType.StoredProcedure);
return Json(result.ToDataSourceResult(request));
}
}
Does EF have other ways to control the authentication process? Or other recommendations for authorizing individual user access to the database?
No, EF Core (as well as previous versions) is agnostic to this concern, i.e. it assumes that the underlying database connection will be capable of accessing the database.
Do you know that the minimal thing is that needs to run in the delegate passed to RunImpersonated? Is it just opening the connection or also any command execution?
Also, I think the code snippets from @madrianr are using Dapper, not EF Core 😸.
I don't know how the SQL auth protocol works. I assume it's per connection rather than per command. It would be pretty obvious if we could look at the src for the client.
Closing this issue because it isn't clear to me if there is an issue remaining. If you feel there's still an issue, please re-open this issue or log a new issue with complete details of the problem. Thanks!
Activity
Tratcher commentedon Nov 1, 2016
You should read up on these threads:
aspnet/IISIntegration#75
https://github.com/dotnet/corefx/issues/9996
ilanc commentedon Nov 2, 2016
Fantastic that appears to work thanks @Tratcher. I'm using:
plus in .cshtml:
and getting:
I'll check this works with the SQL connection next.
ilanc commentedon Nov 2, 2016
Ok it's not quite working - but I expect there's something I've done wrong. If I browse the website on the server (i.e. within a remote desktop session) then it works but not when I browse from another computer (
SqlException: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.).I'll look into it further tomorrow - think its the same bug you mentioned in one of the other threads. I'm using .net 4.5.1 btw - I see you had a solution for 4.6.
Code:
Tratcher commentedon Nov 2, 2016
This sounds like the same delegation issue I had with HttpClient. You can use the WindowsIdentity locally but not for outbound requests.
ilanc commentedon Nov 3, 2016
My reading of https://github.com/dotnet/corefx/issues/9996 was that impersonation is working for .net 4.6. (with
Impersonate()) but not .net core. (withRunImpersonated(..)) Is that correct?I've tried .net 4.6.1 and it doesn't work with
Impersonate()- it's still using userNT AUTHORITY\ANONYMOUS LOGON)ilanc commentedon Nov 3, 2016
Demo repo here: https://github.com/ilanc/AspNetImpersonate
Tratcher commentedon Nov 7, 2016
@divega can you have someone try delegated windows auth with SQL client?
Tratcher commentedon Nov 7, 2016
@ilanc you may also want to try it with WebListener instead of IIS+Kestrel. https://github.com/aspnet/weblistener
divega commentedon Nov 7, 2016
@saurabh500 @corivera does this thread ring any bells? From https://github.com/dotnet/corefx/issues/2191 it seems that there is something SqlClient on .NET Core still needs to do to support impersonation and delegation?
saurabh500 commentedon Nov 8, 2016
@divega From the issue and the repro code, the issue is related to .Net Framework 4.6.1
@ilanc project.json content
"frameworks": { "net461": { } },For .Net core on Windows, the
WindowsIdentity.GetCurrent()API is used to retrieve the user connecting to the DataBase. If the impersonation was successful, the SqlClient should be able to get the correct user to login to the DB.saurabh500 commentedon Nov 8, 2016
@ilanc I am running the application using
dotnet runIt runs successfully on localhost:5000
I don't see any authentication request. How do I get the authentication to ask for credentials?
ilanc commentedon Nov 8, 2016
Hi @saurabh500. Did you see the readme.md on https://github.com/ilanc/AspNetImpersonate:
Now do 2 things:
Working when logged in on server
Not working when remote browsing
ilanc commentedon Nov 8, 2016
My site is setup to run as the pass-through user

saurabh500 commentedon Nov 8, 2016
@ilanc I hosted this app in IIS and enable authentication the way you have instructed above.
I visited the URL on the localhost

From a different machine
I also tried this from @corivera 's machine. I got an error message stating that the authentication for corivera failed.
Then I added corivera to the users on the SqlServer and the authentication went through and I could see the data from the server.
(I don't have screenshots for this)
For Net Framework 461 the Impersonation seems to be working right.
Let me know if I missed out any steps or if you have any other questions/instructions.
saurabh500 commentedon Nov 8, 2016
My environment
IIS server 8.5 on Windows Server 2012 R2
Client browser Chrome on OS Windows Server 2012 R2, Windows 8.1 and Windows 10
19 remaining items
madrianr commentedon Oct 25, 2017
Hello,
I'm not sure but is "aspnet core app with windows auth and Trusted_Connection connectionString" running now with ASP.NET Core 2.0 or not?
I use a ASP.NET Core 2.0 (targeting NET 4.6.1) and the following Code (Middleware) to have the current user logon to sqlserver but always the 'NT AUTHORITY\ANONYMOUS LOGON' connects to the sqlserver...
Please help - I need to have the current user connect to sqlserver...
robert
Tratcher commentedon Oct 25, 2017
RunImpersonated is not async so that middleware does not work. Where did you get that?
No, there have been no improvements here for 2.0.
madrianr commentedon Oct 26, 2017
Hi, after some investigation the code in my last post works (app.UseMiddleware();)
It was necessary to set the SPN on the Domain Controller for the Webserver like:
ie.
and in IIS only Windows Authentication with Negotiate and NTLM...
robert
Tratcher commentedon Oct 31, 2017
ASYNC IMPERSONATION IS A TRAP. It will only work if your application pipeline runs synchronously. I'm going to start removing comments / samples that propose it so others don't make the same mistake.
Impersonation should only be done at the call site where it's required, and that action must be completed synchronously within the RunImpersonated call.
madrianr commentedon Oct 31, 2017
Hi,
Does this mean it is not possible to make a database call "async" like this?
there are so many posts which make it not clear how to use it the right way...
in my application it is important that every database call is made by the current logged on user, so it would be nice if Microsoft can clarify, how to do this in an ASP.NET MVC Core 2 Applicatuion the right way!
robert
Tratcher commentedon Oct 31, 2017
Correct, async operations cannot be combine with impersonation.
@divega accessing the DB as the authenticated user is the most requested use of impersonation. Does EF have other ways to control the authentication process? Or other recommendations for authorizing individual user access to the database?
madrianr commentedon Oct 31, 2017
Ok - to really clarify that:
if this is true, this is a great disadvantage of ASP.NET Core and contradict with the Middleware logic of ASP.NET Core - isn't it (so many repeated code)?
so this Action should work?
Tratcher commentedon Oct 31, 2017
Yes, that action looks correct.
Yes middleware would be a nice way to deal with this in a central location, but we need new async impersonation APIs from .NET Core to make it work correctly. See https://github.com/dotnet/corefx/issues/24977
divega commentedon Nov 2, 2017
@Tratcher sorry for the delayed response.
No, EF Core (as well as previous versions) is agnostic to this concern, i.e. it assumes that the underlying database connection will be capable of accessing the database.
Do you know that the minimal thing is that needs to run in the delegate passed to
RunImpersonated? Is it just opening the connection or also any command execution?Also, I think the code snippets from @madrianr are using Dapper, not EF Core 😸.
Tratcher commentedon Nov 2, 2017
I don't know how the SQL auth protocol works. I assume it's per connection rather than per command. It would be pretty obvious if we could look at the src for the client.
madrianr commentedon Nov 3, 2017
We use Insight.Database (https://github.com/jonwagner/Insight.Database) not Dapper but it is simmilar...
robert
Eilon commentedon Apr 3, 2018
Closing this issue because it isn't clear to me if there is an issue remaining. If you feel there's still an issue, please re-open this issue or log a new issue with complete details of the problem. Thanks!
Added TCP client sample to HubSample (#1805)