Asp.net OWIN Web API Windows服务-Windows身份模拟

Asp.net OWIN Web API Windows服务-Windows身份模拟,asp.net,angularjs,windows-authentication,owin,asp.net-web-api2,Asp.net,Angularjs,Windows Authentication,Owin,Asp.net Web Api2,这是一个内部网应用程序 我有一个WebAPI Owin自托管应用程序在Windows服务器上以服务帐户运行 前端是AngularJS,它通过这个Web API与数据库对话 我想要的是,当在需要数据库交互的API上调用任何操作时,将使用用户凭据连接到数据库,而不是服务帐户本身 我正在使用Windows身份验证,并且在Startup类的httpListener上启用了Ntlm身份验证,并且我能够对用户进行身份验证 当我向Web api提交请求时,我可以看到Thread.CurrentPrincipa

这是一个内部网应用程序

我有一个WebAPI Owin自托管应用程序在Windows服务器上以服务帐户运行

前端是AngularJS,它通过这个Web API与数据库对话

我想要的是,当在需要数据库交互的API上调用任何操作时,将使用用户凭据连接到数据库,而不是服务帐户本身

我正在使用Windows身份验证,并且在Startup类的httpListener上启用了Ntlm身份验证,并且我能够对用户进行身份验证

当我向Web api提交请求时,我可以看到Thread.CurrentPrincipal返回当前用户,但数据库连接失败,因为它试图使用服务帐户而不是用户凭据连接到数据库


请告诉我如何从Web API将用户凭据传递到数据库

您应该像这样模拟调用用户:

public void PerformDBOperationAsCallingUser()
{
    WindowsIdentity callingUser = (WindowsIdentity)Thread.CurrentPrincipal.Identity;

    using (WindowsImpersonationContext wic = callingUser.Impersonate())
    {
        // do your impersonated work here...
        // check your identity like this:
        var name = WindowsIdentity.GetCurrent().Name;
    }
}

使用这段代码作为您工作单元的一部分会很好。但这取决于您设计的其余部分。

如果您需要与登录到您的应用程序的用户连接,您可以模拟他的凭据来访问数据库。像这样的东西可能有用

public static void Test()
{
    WindowsIdentity ident= (WindowsIdentity)HttpContext.Current.User.Identity
    using (WindowsImpersonationContext ctx = ident.Impersonate())
    {
        using (SqlConnection con = new SqlConnection("Data Source=YourServer;Initial Catalog=YourDatabase;Persist Security Info=False;Integrated Security=SSPI"))
        {
            con.Open();
        }
        ctx.Undo();
    }
}

@用户1236667很高兴听到!