【问题标题】:How can I run Internet Explorer Selenium tests as a specific domain user?如何以特定域用户身份运行 Internet Explorer Selenium 测试?
【发布时间】:2015-03-18 17:05:45
【问题描述】:

我有一个使用 Windows 身份验证来控制访问的 ASP.NET MVC 网站。我想要一个 specflow selenium 测试,通过尝试以非授权用户身份访问该站点来检查配置是否正确。

由于我们使用域帐户来控制访问,因此没有用户名/密码登录屏幕。当前用户的凭据由浏览器自动传递给站点。

所以对于我的 Selenium 测试,我需要能够以特定用户身份运行 Internet Explorer。

我找到了许多关于 windows 模拟的文章,我可以在测试运行期间切换到我的测试用户(使用来自 http://support.microsoft.com/kb/306158 的代码)。但是,如果我随后创建 InternetExplorerDriver,它会使用我的凭据而不是测试用户的凭据启动 Internet Explorer(尽管这个问题和答案表明它应该可以工作 https://sqa.stackexchange.com/questions/2277/using-selenium-webdriver-with-windows-authentication)。

我也可以作为我的测试用户显式启动 Internet Explorer 进程,但我看不到将 InternetExplorerDriver 绑定到已经运行的 Internet Explorer 进程的方法,因此这可能是死路一条。

下面是我的代码,基本上取自上面的 MSDN 页面。在调试器中,我可以看到 WindowsIdentity.GetCurrent().Name 在测试的所有步骤中都是“testUser”。

namespace MyProject.Specs
{
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using TechTalk.SpecFlow;

[Binding]
public class AuthorisationSteps
{
    public const int LOGON32_LOGON_INTERACTIVE = 2;
    public const int LOGON32_PROVIDER_DEFAULT = 0;
    private static WindowsImpersonationContext impersonationContext;
    private static IWebDriver driver;

    [BeforeScenario]
    public static void impersonateUser()
    {
        if (!impersonateValidUser("testUser", "testDomain", "password"))
        {
            throw new Exception();
        }
        driver = new InternetExplorerDriver();
    }

    [AfterScenario]
    public static void cleanupUser()
    {
        undoImpersonation();
        driver.Quit();
    }

    [Given(@"I am an unauthorised user")]
    public void GivenIAmAnUnauthorisedUser()
    {
        var temp = WindowsIdentity.GetCurrent().Name;
    }

    [When(@"I go to the home page")]
    public void WhenIGoToTheHomePage()
    {
        var temp = WindowsIdentity.GetCurrent().Name;
        driver.Navigate().GoToUrl(BaseUrl);
    }

    [Then(@"I should see an error page")]
    public void ThenIShouldSeeAnErrorPage()
    {
        var temp = WindowsIdentity.GetCurrent().Name;
        Assert.That(driver.Title.Contains("Error"));
    }

    [DllImport("advapi32.dll")]
    public static extern int LogonUserA(String lpszUserName,
                                        String lpszDomain,
                                        String lpszPassword,
                                        int dwLogonType,
                                        int dwLogonProvider,
                                        ref IntPtr phToken);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int DuplicateToken(IntPtr hToken,
                                            int impersonationLevel,
                                            ref IntPtr hNewToken);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool RevertToSelf();

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern bool CloseHandle(IntPtr handle);

    private static bool impersonateValidUser(String userName, String domain, String password)
    {
        WindowsIdentity tempWindowsIdentity;
        var token = IntPtr.Zero;
        var tokenDuplicate = IntPtr.Zero;

        if (RevertToSelf())
        {
            if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                LOGON32_PROVIDER_DEFAULT, ref token) != 0)
            {
                if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                {
                    tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                    impersonationContext = tempWindowsIdentity.Impersonate();
                    if (impersonationContext != null)
                    {
                        CloseHandle(token);
                        CloseHandle(tokenDuplicate);
                        return true;
                    }
                }
            }
        }
        if (token != IntPtr.Zero)
        {
            CloseHandle(token);
        }
        if (tokenDuplicate != IntPtr.Zero)
        {
            CloseHandle(tokenDuplicate);
        }
        return false;
    }

    private static void undoImpersonation()
    {
        impersonationContext.Undo();
    }
}

}

【问题讨论】:

  • 也许可以尝试一下:将driver 实例化放在impersonateValidUser(..) 之前
  • 感谢您的想法,但恐怕它不能解决问题
  • 也许可以尝试通过runas /user:USER@DOMIAN path\to\mstest.exe ...从Windows命令行开始你的测试
  • 这可能行得通,但您需要为每个用户踢一次。现在我已经停止研究这个,因为我只有两个需要它的测试,我可以在几分钟内手动运行它们。
  • 有人在 Java 的上下文中提出了类似的问题:stackoverflow.com/questions/18017883/… - 但它仍然“未回答”。

标签: asp.net-mvc selenium selenium-webdriver windows-authentication specflow


【解决方案1】:

这个similar question 链接到这个Microsoft support article。基本上你需要

System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext = 
((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
IWebDriver webDriver = new InternetExplorerDriver();
// do your stuff here.
impersonationContext.Undo();

支持文章中有关于模拟特定用户的附加代码。

【讨论】:

  • 我认为这是 Dan 已经在使用的代码。这与他在问题中链接到的知识库文章相同。
  • 模拟有效,但 Internet Explorer 用户对我没有改变。
【解决方案2】:

你有几台旧电脑吗?或者某些虚拟机的容量?

如果是这样,请构建一个 Selenium Grid 设置,并将其中一个配置为以所需域用户身份自动登录,另一个以非域用户身份登录。
http://code.google.com/p/selenium/wiki/Grid2

【讨论】:

    【解决方案3】:

    我在为需要窗口身份验证的基于 Web 的应用程序执行自动化项目时遇到了同样的问题。但是,我已经通过使用 firefox 实现了这一点,以下是实现它的步骤。

    火狐设置

    1. 打开您的系统的运行对话框并键入“firefox.exe -p”(在运行此命令之前关闭您的 Firefox 浏览器)http://www.wikihow.com/Create-a-Firefox-Profile
    2. 点击创建配置文件并根据要求提供名称
    3. 选择创建的配置文件并启动浏览器并打开插件管理器(工具 - 插件)
    4. 搜索“AutoAuth”并安装它。它会要求重新启动,执行它
    5. 重启 Firefox 后,打开 URL 后,它会要求您进行身份验证
    6. 输入用户名和密码 - 提交,Firefox 会要求您记住密码
    7. 点击记住,它会将密码保存在 Firefox 配置文件中
    8. 复制创建的 Firefox 配置文件并将其保存到所需文件夹
    9. 在您使用 Firefox 驱动程序创建的配置文件上方的 SELENIUM 脚本调用中并传递相同的 URL,它不会询问身份验证对话框

    这在我的项目中非常成功。

    【讨论】:

      【解决方案4】:

      我们在 2 年内对 IE 和 Chrome 使用 https://stackoverflow.com/a/31540010/3489693 方法。效果很好

      【讨论】:

        【解决方案5】:

        这实际上是可能的。我遇到了你遇到的确切问题。基本上,这是您需要执行的步骤。

        1. 在后台使用其他用户的凭据手动启动浏览器驱动程序

          Process driverProcess;
          string driverPath; // The path to Selenium's IE driver.
          ProcessStartInfo info = new ProcessStartInfo(driverPath)
          {
              UserName = "UserName", // The user name.
              Password = new SecureString(), // The password for the user.
              UseShellExecute = false,
              LoadUserProfile = true,
              Arguments = "about:blank"
          };
          // Start the driver in background thread
          Thread startThread = new Thread(
              () => {
                  try
                  {
                      driverProcess = Process.Start(info);
                      driverProcess.WaitForExit();
                  }
                  catch
                  {
                      // Close the process.
                  }
              })
          {
              IsBackground = true
          };
          startThread.Start();
          
        2. 使用远程 Web 驱动程序连接手动启动的浏览器驱动程序实例。

          var remoteDriver = new RemoteWebDriver(Uri("http://localhost:5555"), DesiredCapabilities.InternetExplorer());
          
        3. 完成后记得关闭/退出/终止驱动进程和浏览器实例。

          // Close the process when done.
          if (driverProcess != null)
          {
              // Free managed resources
              if (!driverProcess.HasExited)
              {
                  driverProcess.CloseMainWindow();
                  driverProcess.WaitForExit(5000);
                  // Kill the process if the process still alive after the wait
                  if (!driverProcess.HasExited)
                  {
                      driverProcess.Kill();
                  }
          
                  driverProcess.Close();
              }
          
              driverProcess.Dispose();
              driverProcess = null;
          }
          

        【讨论】:

        • 第 1 步缺少手动启动该过程的方式 - 特别是 info 对象。
        • @RickGlos 我更新了第 1 步,包括如何获取 info 对象。
        • 谢谢,有了这个额外的清晰消息,我能够得到这个工作,虽然我们是用 Chrome 做的,但它似乎就像将 driverPath 更改为使用 chromedriver 一样简单与IEDriverServer 相比。我们还需要一遍又一遍地重用它,所以我很快就会发布一个答案,我们现在在许多基于你的方法中使用它。再次感谢!
        【解决方案6】:

        我们有许多企业客户端对面向 Intranet 的应用程序使用 Windows 身份验证,并且我们开始运行许多 Selenium 测试以进行确认、回归等。

        我们从 Steven 的回答中获取了有用的代码,并将其重构为一个可重用的类,类似于其他对我们不起作用的 Impersonate 帖子,因为我们希望测试在本地开发和部署中都可以工作作为 Visual Studio Team System 发布过程的一部分。

        uri 方法在本地不起作用,使用 Win32 本机方法的模拟方法也不起作用。

        这个有效,所以就在这里。

        使用 Steven 的代码重构为帮助程序的测试示例

        [TestMethod]
        public void ThisApp_WhenAccessedByUnathorizedUser_ShouldDisallowAccess()
        {
            string userName = "ThisAppNoAccess";
            string password = "123456";
            string domainName = Environment.MachineName;
            using (new Perkins.Impersonator(userName, domainName, password))
            {
                // - Use Remote Web Driver to hook up the browser driver instance launched manually.
                using (var driver = new RemoteWebDriver(new Uri("http://localhost:9515"), DesiredCapabilities.Chrome()))
                {
                    var desiredUri = Helper.Combine(Helper.BaseURL, "/ThisApp/#/appGrid");
                    TestContext.WriteLine("desiredUri: {0}", desiredUri);
                    driver.Navigate().GoToUrl(desiredUri);
                    Helper.WaitForAngular(driver);
                    var noPermissionNotificationElement = driver.FindElementByXPath("//div[@ng-show='!vm.authorized']/div/div/div/p");
                    var showsNoPermissionNotification = noPermissionNotificationElement.Text.Contains("You do not have permissions to view ThisApp.");
                    Assert.AreEqual(true, showsNoPermissionNotification, "The text `You do not have permissions to view ThisApp.` is not being displayed!");
                }
            }
        }
        

        助手类

        // Idea from http://stackoverflow.com/a/34406336/16008
        // - Launch the browser driver manually with other user's credentials in background
        public class Perkins
        {
            public class Impersonator : IDisposable
            {
                Process _driverProcess = null;
                string _driverPath = @"chromedriver.exe";
                /// <summary>
                /// Impersonates the specified user account by launching the selenium server under that account.  Connect to it via RemoteWebDriver and localhost on port 9515.
                /// </summary>
                /// <remarks>
                /// We may later want to enhance this by allowing for different ports, etc.
                /// </remarks>
                /// <param name="userName">Name of the user</param>
                /// <param name="domainName">Name of the domain or computer if using a local account.</param>
                /// <param name="password">The password</param>
                public Impersonator(string userName, string domainName, string password)
                {
                    ProcessStartInfo processStartInfo = new ProcessStartInfo(_driverPath);
                    processStartInfo.UserName = userName;
                    System.Security.SecureString securePassword = new System.Security.SecureString();
                    foreach (char c in password)
                    {
                        securePassword.AppendChar(c);
                    }
                    processStartInfo.Password = securePassword;
                    processStartInfo.Domain = domainName; // this is important, mcollins was getting a 'stub received bad data' without it, even though rglos was not
                    processStartInfo.UseShellExecute = false;
                    processStartInfo.LoadUserProfile = true; // this seemed to be key, without this, I get Internal Server Error 500
                    Thread startThread = new Thread(() =>
                    {
                        _driverProcess = Process.Start(processStartInfo);
                        _driverProcess.WaitForExit();
                    })
                    { IsBackground = true };
                    startThread.Start();
                }
                public void Dispose()
                {
                    // - Remember to close/exit/terminate the driver process and browser instance when you are done.
                    if (_driverProcess != null)
                    {
                        // Free managed resources
                        if (!_driverProcess.HasExited)
                        {
                            _driverProcess.CloseMainWindow();
                            _driverProcess.WaitForExit(5000);
                            // Kill the process if the process still alive after the wait
                            if (!_driverProcess.HasExited)
                            {
                                _driverProcess.Kill();
                            }
                            _driverProcess.Close();
                        }
                        _driverProcess.Dispose();
                        _driverProcess = null;
                    }
                }
            }
        }
        

        也许这会帮助其他有同样问题的人。

        【讨论】:

        • 感谢这堂课;这真的有助于弄清楚我想做什么。不过,我在登录信息方面遇到了问题,我在这里发了一个帖子:stackoverflow.com/questions/47687030/…你知道我怎么能克服这个/我做错了什么吗?使用您未修改的代码时,我也会遇到同样的错误。
        • 这段代码的逻辑很清楚:首先使用impersonator启动一个chrome驱动进程,然后通过Json Wire Protocol和RemoteWebDriver连接驱动。非常聪明,干得好!
        【解决方案7】:

        因此,问题试图规避的问题似乎与 NTLM 自动登录有关。见Google Chrome and NTLM Auto Login Using Windows Authentication

        上面的解决方案对我不起作用,因为自动登录可以成功地通过我系统上的任何用户进行身份验证,所以我使用哪个用户来模拟并不重要。

        但是,我注意到您可以通过将 localhost 替换为任何其他域名(例如本地 IP 地址)来超越自动登录。无需冒充:)

        【讨论】:

          【解决方案8】:

          这可能/可能不起作用。

          • 尝试在“CHROME”中启动您的网站。
          • 按 F-12,转到应用程序选项卡 -> Cookies -> 单击您的站点链接。在左侧查找代表您的会话 ID 的内容,可能是代表用户会话的 JSESSIONID 或类似名称,复制它。
          • 现在打开您的 Internet Explorer,
          • 按 F-12 并通过在控制台窗口中运行此命令手动创建该 JSESSIONID(或类似键)

          document.cookie = "JSESSIONID=your-session-id-from-chrome"

          • 点击播放按钮执行脚本
          • 刷新浏览器

          【讨论】:

            猜你喜欢
            • 2015-05-05
            • 2018-06-06
            • 1970-01-01
            • 1970-01-01
            • 2017-09-14
            • 1970-01-01
            • 2015-03-11
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多