1

这是一个Intranet应用程序。OWIN Web API Windows服务 - Windows身份模拟

我有一个WebAPI Owin selfhosting应用程序在Windows服务器下运行的服务帐户。

前端是AngularJS,它通过这个Web API与数据库进行通信。

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

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

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

请告诉我如何传递用户凭据从网络API数据库

回答

2

你应该扮演这样主叫用户:

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; 
    } 
} 

将是不错的使用这段代码作为decorator围绕您的工作单位。但取决于你的设计的其余部分。

+0

谢谢,它为我工作 – armulator 2014-10-21 21:49:09

+0

@ user1236667很高兴听到! – 2014-10-22 20:35:26

0

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

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(); 
    } 
} 
相关问题