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(); 
    } 
} 
相關問題