简体   繁体   中英

How to override basic authentication in selenium2 with Java using chrome driver?

How to override basic authentication in selenium2 chrome driver? I am facing an issue in my project where chrome "Authentication required" popup is coming which is blocking webdriver to continue navigation. Please find the attached screenshot for the same. 在此输入图像描述 I am using following code to instantiate chrome driver,

private WebDriver driver;
@Override
protected void setUp() throws Exception {
    super.setUp();
    System.setProperty("webdriver.chrome.driver", "C:/Selenium/chromedriver.exe");
    driver = new ChromeDriver();
}
@Override
protected void tearDown() throws Exception {
    // TODO Auto-generated method stub
    super.tearDown();
}

Could you please help -

Thanks,

I've struggled with the same problem over an hour and finally @kenorb's solution rescued me. To be short you need to add a browser extension that does the authentication for you (since Selenium itself can't do that!).

Here is how it works for Chrome and Python :

  1. Create a zip file proxy.zip containing two files:

background.js

var config = {
    mode: "fixed_servers",
    rules: {
      singleProxy: {
        scheme: "http",
        host: "YOU_PROXY_ADDRESS",
        port: parseInt(YOUR_PROXY_PORT)
      },
      bypassList: ["foobar.com"]
    }
  };

chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});

function callbackFn(details) {
    return {
        authCredentials: {
            username: "YOUR_PROXY_USERNAME",
            password: "YOUR_PROXY_PASSWORD"
        }
    };
}

chrome.webRequest.onAuthRequired.addListener(
        callbackFn,
        {urls: ["<all_urls>"]},
        ['blocking']
);

Don't forget to replace YOUR_PROXY_* to your settings.

manifest.json

{
    "version": "1.0.0",
    "manifest_version": 2,
    "name": "Chrome Proxy",
    "permissions": [
        "proxy",
        "tabs",
        "unlimitedStorage",
        "storage",
        "<all_urls>",
        "webRequest",
        "webRequestBlocking"
    ],
    "background": {
        "scripts": ["background.js"]
    },
    "minimum_chrome_version":"22.0.0"
}
  1. Add the created proxy.zip as an extension

     from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_extension("proxy.zip") driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=chrome_options) driver.get("http://google.com") driver.close() 

That's it. For me that worked like a charm. If you need to create proxy.zip dynamically or need PHP example then go to the original post

I think you're talking about using NTLM Authentication ( windows integrated authentication ) not Basic Authentication ( where you provider your credentials in URL ). Assuming that here is what you can try for running NTML auth in chrome:

Approach 1

Go to Internet Explorer, and open "Internet Options". Follow following steps:

  • Add your site to either Local intranet or Trusted sites 加
  • 项目清单
  • 项目清单
  • 项目清单
  • 项目清单

After these changes, your chrome authentication should work. If you're wondering that how IE settings effect chrome behavior then, Chrome uses IE security settings for authentication.

Some good resources / credits:

  1. Good details
  2. Selenium issue details

Approach 2

Add your site to Local intranet and don't change anything for user authentication. By default, second option ( Automatic logon only in Intranet sites ) is selected.

您可以尝试将登录凭据添加到url get请求(在Java中):

driver.get("http://username:password@google.com/")

I manage to do that sending the credentials twice. I don't know why, but in the second time the browser sends the packet, the authentication header goes with basic authentication.

My code (using C#):

string url = "http://user:password@google.com/";
IWebDriver webDriver = new ChromeDriver();
webDriver.Navigate().GoToUrl(url);
webDriver.Url = url;

Apart of configuring Network Proxy Preferences , you can set http_proxy in /etc/environment .

Other method is to use Chrome HTTP Private Proxy (which is based on Chrome-proxy-helper ).

Here is PHP example (found in README):

$pluginForProxyLogin = '/tmp/a'.uniqid().'.zip';

$zip = new ZipArchive();
$res = $zip->open($pluginForProxyLogin, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$zip->addFile('/path/to/Chrome-proxy-helper/manifest.json', 'manifest.json');
$background = file_get_contents('/path/to/Chrome-proxy-helper/background.js');
$background = str_replace(['%proxy_host', '%proxy_port', '%username', '%password'], ['5.39.64.181', '54991', 'd1g1m00d', '13de02d0e0z9'], $background);
$zip->addFromString('background.js', $background);
$zip->close();

putenv("webdriver.chrome.driver=/path/to/chromedriver");

$options = new ChromeOptions();
$options->addExtensions([$pluginForProxyLogin]);
$caps = DesiredCapabilities::chrome();
$caps->setCapability(ChromeOptions::CAPABILITY, $options);

$driver = ChromeDriver::start($caps);
$driver->get('https://old-linux.com/ip/');

header('Content-Type: image/png');
echo $driver->takeScreenshot();


unlink($pluginForProxyLogin);

The same logic should work for other languages as well.

More portable solution is reported already on SeleniumHQ GitHub .

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM