asp.net-mvc - 使用 Windows 身份验证在 MVC 应用程序中模拟 Active Directory 用户

标签 asp.net-mvc asp.net-mvc-4 iis windows-authentication impersonation

我正在为 Intranet MVC 应用程序构建一个管理模块。此应用程序实现 Windows 身份验证(用户自动登录)。

目前,我的所有用户体验都基于 HttpContext.User.Identity 数据。

我需要做的是能够模拟用户,以便在他们遇到问题时我可以复制他们的体验。

使用表单例份验证,这非常简单......

我尝试替换 HttpContext 中的 IPrincipal.User 对象,但这只有 getter 而没有 setter。

任何指示将不胜感激。

谢谢。

最佳答案

 using (new Impersonation()){
  // now working in context of whatever user you want
 }

这就是类(class)

 [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public class Impersonation : IDisposable
    {
    private readonly SafeTokenHandle _handle;
    private readonly WindowsImpersonationContext _context;

    //const int Logon32LogonNewCredentials = 9; 
    private const int Logon32LogonInteractive = 2;

    public Impersonation()
    {
        var domain = "your domain;
        var username = "the user";
        var password = "their password";
        var ok = LogonUser(username, domain, password, Logon32LogonInteractive, 0, out _handle);
        if (!ok)
        {
            var errorCode = Marshal.GetLastWin32Error();
            throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
        }
        _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle());
    }

    public void Dispose()
    {
        _context.Dispose();
        _handle.Dispose();
    }

    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true) { }

        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }
}

关于asp.net-mvc - 使用 Windows 身份验证在 MVC 应用程序中模拟 Active Directory 用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22406713/

相关文章:

c# - 使用 mimekit/mailkit 库获取电子邮件的传递状态

asp.net-mvc - MVC 4 OAuth 集成。接下来是什么以及如何从数据提供者那里获取任何信息?

c# - CSS3 动画 无效果

node.js - 不工作 - 在 IIS (iisnode) 上部署 Node 应用程序 - 返回 403 错误

c# - 使用 Entity Framework 时处理 ASP.NET MVC 中的必填字段

asp.net-mvc - 在编辑操作中使用 RowVersion 的 ASP.NET MVC 并发

asp.net-mvc - 为什么我的样式包在 ASP.NET MVC 4 中无法正确呈现?

c# - 每当我更新 edmx 文件时,它都会更改 model1.context.cs 的类名

node.js http-proxy 自定义路由

.net - 有关 Asp.Net 管道和内部请求处理架构的文章/链接