Skip to content

Running a published aspnet core app with windows auth and Trusted_Connection connectionString #1805

Closed

Description

@ilanc

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?

Activity

  1. ilanc commented on Nov 2, 2016

    @ilanc
    Author

    Fantastic that appears to work thanks @Tratcher. I'm using:

    var callerIdentity = User.Identity as WindowsIdentity;
    Action action = () => { ViewData["Testing"] = ($"I am {WindowsIdentity.GetCurrent().Name}!"); };
    WindowsIdentity.RunImpersonated(callerIdentity.AccessToken, action);
    

    plus in .cshtml:

    @System.Security.Principal.WindowsIdentity.GetCurrent().Name
    <br />
    @User.Identity.Name
    <br />
    @ViewData["Testing"]
    

    and getting:

    IIS APPPOOL\test2 
    AM\ICopelyn 
    I am AM\ICopelyn!
    

    I'll check this works with the SQL connection next.

  2. ilanc commented on Nov 2, 2016

    @ilanc
    Author

    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())
                        {
    
    
    
  3. Tratcher commented on Nov 2, 2016

    @Tratcher
    Member

    This sounds like the same delegation issue I had with HttpClient. You can use the WindowsIdentity locally but not for outbound requests.

  4. ilanc commented on Nov 3, 2016

    @ilanc
    Author

    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. (with RunImpersonated(..)) Is that correct?

    I've tried .net 4.6.1 and it doesn't work with Impersonate() - it's still using user NT AUTHORITY\ANONYMOUS LOGON)

  5. Tratcher commented on Nov 7, 2016

    @Tratcher
    Member

    @divega can you have someone try delegated windows auth with SQL client?

  6. Tratcher commented on Nov 7, 2016

    @Tratcher
    Member
  7. divega commented on Nov 7, 2016

    @divega
    Contributor

    @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?

  8. saurabh500 commented on Nov 8, 2016

    @saurabh500

    @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.

  9. saurabh500 commented on Nov 8, 2016

    @saurabh500

    @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?

  10. ilanc commented on Nov 8, 2016

    @ilanc
    Author

    Hi @saurabh500. Did you see the readme.md on https://github.com/ilanc/AspNetImpersonate:

    1. You need to publish the code to a server and run it via iis.
    2. Setup IIS to have windows auth - i.e.
      • IIS manager > your site > Authentication
      • Anonymous Authentication = Disabled
      • Windows Authentication = Enabled

    Now do 2 things:

    1. Browse the site from within your remote desktop connection on your server (i.e. http://localhost/home/about). Here the SQL connection will work because you're logged on as a valid windows user. NB you'll see the user in the title bar of the page - e.g. AM\ICopelyn! in my pic below.
    2. Now browse the site from your machine (i.e. another machine on the same windows domain as the server - http://servername/home/about/). Now you'll get an error - demonstrating that impersonation is not working.

    Working when logged in on server

    image

    Not working when remote browsing

    image

  11. ilanc commented on Nov 8, 2016

    @ilanc
    Author

    My site is setup to run as the pass-through user
    image

    image

  12. saurabh500 commented on Nov 8, 2016

    @saurabh500

    @ilanc I hosted this app in IIS and enable authentication the way you have instructed above.

    image

    I visited the URL on the localhost
    image

    From a different machine

    image

    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.

  13. saurabh500 commented on Nov 8, 2016

    @saurabh500

    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

  14. 19 remaining items

  15. madrianr commented on Oct 25, 2017

    @madrianr

    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...

    
    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...

    robert

  16. Tratcher commented on Oct 25, 2017

    @Tratcher
    Member

    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.

  17. madrianr commented on Oct 26, 2017

    @madrianr

    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...

    robert

  18. Tratcher commented on Oct 31, 2017

    @Tratcher
    Member

    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.

  19. madrianr commented on Oct 31, 2017

    @madrianr

    Hi,

    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!

    robert

  20. Tratcher commented on Oct 31, 2017

    @Tratcher
    Member

    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?

  21. madrianr commented on Oct 31, 2017

    @madrianr

    Ok - to really clarify that:

    • 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));
    }             
        }
    
  22. Tratcher commented on Oct 31, 2017

    @Tratcher
    Member

    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

  23. divega commented on Nov 2, 2017

    @divega
    Contributor

    @Tratcher sorry for the delayed response.

    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 😸.

  24. Tratcher commented on Nov 2, 2017

    @Tratcher
    Member

    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.

  25. madrianr commented on Nov 3, 2017

    @madrianr
  26. Eilon commented on Apr 3, 2018

    @Eilon
    Contributor

    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!

  27. ghost locked as resolved and limited conversation to collaborators on Dec 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions