【问题标题】:OWIN Web API Windows Service - Windows Identity ImpersonationOWIN Web API Windows 服务 - Windows 身份模拟
【发布时间】:2014-10-21 03:45:53
【问题描述】:

这是一个 Intranet 应用程序。

我有一个 WebAPI Owin 自托管应用程序在服务帐户下的 Windows Server 上运行。

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

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

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

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

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

【问题讨论】:

    标签: asp.net angularjs windows-authentication owin asp.net-web-api2


    【解决方案1】:

    您应该像这样冒充调用用户:

    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 会很好。但取决于您设计的其余部分。

    【讨论】:

    • @user1236667 很高兴听到!
    【解决方案2】:

    如果您需要与登录到您的应用的用户建立联系,您可以模拟他的凭据来访问数据库。这样的事情可能会奏效。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-18
      • 2016-07-17
      • 1970-01-01
      • 2016-06-10
      • 2015-04-16
      • 2017-11-26
      • 2015-11-11
      • 2014-03-01
      相关资源
      最近更新 更多