【问题标题】:ASP.NET CORE 1.0, ImpersonationASP.NET CORE 1.0,模拟
【发布时间】:2016-05-12 21:00:50
【问题描述】:

我正在编写一个 Intranet 应用程序。 project.json 中的目标框架是 dnx451。 这是我的发布命令:

dnu publish --runtime dnx-clr-win-x86.1.0.0-rc1-update1 --no-source

数据库连接字符串:

Server=name;Database=name;Trusted_Connection=True;

我正在尝试模拟数据库访问,但它不起作用。当我启动应用程序时,我的 Windows 用户被识别,并在右上角显示 Hello, Domain\Username。一旦我尝试访问数据库,我就会收到错误“用户域\计算机名登录失败”。如果我在我的用户下运行应用程序池,那么一切正常。

IIS: .NET CLR 版本是 v4.0,托管管道模式经典,身份是 ApplicationPoolIdentity。 网站身份验证:已启用 ASP.NET 模拟和 Windows 身份验证。

我需要做些什么来改变模拟最终起作用?

【问题讨论】:

    标签: c# asp.net-core impersonation dnx asp.net-core-1.0


    【解决方案1】:

    如果你想让每个页面请求都冒充用户,你可以配置自己的Middleware在MVC之前运行;

    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 {
                WindowsIdentity.RunImpersonated(winIdent.AccessToken, () => {
                    next.Invoke(context).Wait();
                });
            }
        }
    }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
        ....
        app.UseMiddleware<Impersonate>();
        app.UseMvc(...);
        ...
    }
    

    【讨论】:

    • 该代码完美地失败了最新的稳定核心 mvc =(
    • 抱歉,我错误地尝试异步调用下一个处理程序,这意味着模拟可能仅适用于第一个等待的 I/O 调用。然后异步任务将返回,RunImpersonated 将返回,我们将等待 Web 管道的其余部分。相反,模拟必须阻塞请求线程,直到下一个委托完成(如上所述?)。虽然可能仍然有异步代码在不同的线程上运行......
    【解决方案2】:

    Core 不支持模拟,因为所有 Web 代码都在由 Kestrel 托管的 proc 之外。如果你想这样做,你需要把当前的 Principal 作为一个 WindowsPrincipal,然后在你需要的地方manually impersonate

    需要注意的一点是,在 RC1 中您没有获得 WindowsPrincipal,因此您现在无法执行此操作。它会在 RC2 中修复。

    【讨论】:

    • blowdart 的解决方案会起作用,我只是针对 RC1 对其进行了测试。我使用了针对 4.5.1 的更新版本:impersonation.codeplex.com,我相信它源自同一个 MSDN 示例,该示例已经存在了一段时间。
    • @blowdart:即使我只针对 dnx-clr,它仍然是核心吗?
    • @blowdar:有没有 RC2 测试版,我可以在其中获得 WindowsPrincipal?
    • @Dani 没有。它仅适用于每晚构建。
    • @blowdart RC2 现已发布,您能否更新您的答案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多