How to set Proxy Authentication in seleniumWebdriver for Chrome Browser
Asked Answered
M

7

8

I'm trying to Automate a web application selenium 2.0 [webdriver+java].The web application is currently deployed in our UAT servers on our local network.My test cases are executing, but I have to manually enter the Proxy Authentication details for my Chrome instance at the start of the test execution. I have tried all the solutions provided on stack overflow but still, the authentication message pops out.

enter image description here

This is the code I'm using in my driver initializing process

package com.misyn.ess.ui;

import java.util.Arrays;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

/**
 *
 * @author User
 */
public class DriverClass {

    private String baseUrl;
    private String driverPath;
    private String driverName;
    private static WebDriver driver;
    private static DriverClass driverClass;

        private DriverClass() {
            try {
                baseUrl = "http://192.168.0.10:8282/ess";
                driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
                driverName = "webdriver.chrome.driver";

                //Set the location of the ChromeDriver
            System.setProperty(driverName, driverPath);
            //Create a new desired capability
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            // Create a new proxy object and set the proxy
            Proxy proxy = new Proxy();
            proxy.setHttpProxy("192.168.0.200:3128");
            proxy.setSocksUsername("avishka");
            proxy.setSocksPassword("12345678");
            //Add the proxy to our capabilities 
            capabilities.setCapability("proxy", proxy);
            //Start a new ChromeDriver using the capabilities object we created and added the proxy to
            driver = new ChromeDriver(capabilities);

            //Navigation to a url and a look at the traffic logged in fiddler
            driver.navigate().to(baseUrl);


    //            System.setProperty(driverName, driverPath);
    //            driver = new ChromeDriver();
    //            driver.get(baseUrl);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

Can anyone give me a solution how to give this proxy username and password thing from the application itself than manually entering details on the pop-up(Authentication), any help would be much appreciated.Thanks

the currently answered one is only for

As of Selenium 3.4 it is still in beta Right now implementation is only done for InternetExplorerDriver

Where I'm using selenium 3.0 and Google Chrome as my web browser.

Minivet answered 6/7, 2017 at 5:56 Comment(13)
which chrome version you are using?Galangal
Version 59.0.3071.115 (Official Build) (64-bit) @santhoshkumarMinivet
Then i think we need to use AUTOIT toolGalangal
what is AUTOIT toolMinivet
Any code or tutorial how to use it for proxy authentication @santhoshkumarMinivet
learn-automation.com/… This tutorial is for Firefox..., not sure about chromeGalangal
Let us continue this discussion in chat.Minivet
Possible duplicate of How to handle authentication popup with Selenium WebDriver using JavaSiamese
@Siamese if you read the How to handle authentication popup with Selenium WebDriver using Java which you linked, you can notice the answer is for Selenium 3.4 Beta and the IE browser, which I'm working on Selenium 3.0 and my web browser is Google Chrome. As of Selenium 3.4, it is still in beta Right now implementation is only done for InternetExplorerDriver the most rated answer FYIMinivet
@Siamese I've tried the example you gave me as well. WebDriverWait wait = new WebDriverWait(driver, 10); Alert alert = wait.until(ExpectedConditions.alertIsPresent()); alert.authenticateUsing(new UserAndPassword("avishka", "12345678")); Below error was displayed on the console org.openqa.selenium.TimeoutException: Expected condition failed: waiting for alert to be present (tried for 10 second(s) with 500 MILLISECONDS interval) Build info: version: '3.4.0', revision: 'unknown', time: 'unknown' Didn't solve the problem.Minivet
@VaasPerera Yes That is for IE. For Chrome you have to go with AutoIt or any Image Based approachSiamese
Yeap, just got to know it from santhosh, ill look in to it and post a reply to this , thread soon!Minivet
Prior to chrome v58, you could use credentials embedded in the URL (e.g. http://username:[email protected]). But chrome v59+ will "block requests for subresources that contain embedded credentials", so that (likely) won't be an option. Here's the link to the documentation: chromestatus.com/feature/5669008342777856.Olander
S
5

You can do via MultiPass for HTTP basic authentication

Download the extension from
https://chrome.google.com/webstore/detail/multipass-for-http-basic/enhldmjbphoeibbpdhmjkchohnidgnah

Download the extension as crx. You can get it as crx from chrome-extension-downloader

After that the config is simple.

import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

/**
 *
 * @author Phystem
 */
public class ChromeAuthTest {

    WebDriver driver;

    public ChromeAuthTest() {
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
    }

    private void initDriver() {
        ChromeOptions cOptions = new ChromeOptions();
        cOptions.addExtensions(new File("MultiPass-for-HTTP-basic-authentication_v.crx"));
        driver = new ChromeDriver(cOptions);
        configureAuth(
                "https://the-internet.herokuapp.com/basic_auth",
                "admin",
                "admin");
    }

    private void configureAuth(String url, String username, String password) {
        driver.get("chrome-extension://enhldmjbphoeibbpdhmjkchohnidgnah/options.html");
        driver.findElement(By.id("url")).sendKeys(url);
        driver.findElement(By.id("username")).sendKeys(username);
        driver.findElement(By.id("password")).sendKeys(password);
        driver.findElement(By.className("credential-form-submit")).click();
    }

    public void doTest() {
        initDriver();
        driver.get("https://the-internet.herokuapp.com/basic_auth");
        System.out.println(driver.getTitle());
        driver.quit();
    }

    public static void main(String[] args) {
        new ChromeAuthTest().doTest();
    }
}

I have used a sample site for testing.

Provide your url,username and password in the configure Auth function and try

Siamese answered 6/7, 2017 at 13:32 Comment(6)
Did you try this from a direct connection?Minivet
the application that I'm trying to access is "192.168.0.10:8282/ess" but my proxy authentication pop up, comes from "192.168.0.200:3128" which is the proxy for the network. And I have tried your solution it shows this in the console java.lang.IllegalArgumentException: C:\Users\User\Documents\NetBeansProjects\Ess\MultiPass-for-HTTP-basic-authentication_v.crx does not exist i've used configureAuth() belowMinivet
You have to download the crx file.. Have you done that?Siamese
yes, I have. from chrome web store. it is also running on my Chrome browser as an extension.Minivet
You have to use the chrome extension downloader and download it as crx file.Siamese
I've tried chrome extension downloader and the solutions you gave @Madhan. finally came up with a solution and will answer it as for the answer to the question.Minivet
M
4
    public class DriverClass {

    private String baseUrl;
    private String driverPath;
    private String driverName;
    private static WebDriver driver;
    private static DriverClass driverClass;

    public DriverClass() {
        try {
            baseUrl = "http://192.168.0.10:8282/ess";
            driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
            driverName = "webdriver.chrome.driver";
            System.setProperty(driverName, driverPath);

            Proxy proxy = new org.openqa.selenium.Proxy();
            proxy.setSslProxy("192.168.0.200" + ":" + 3128);
            proxy.setFtpProxy("192.168.0.200" + ":" + 3128);
            proxy.setSocksUsername("avishka");
            proxy.setSocksPassword("12345678");

            DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
            desiredCapabilities.setCapability(CapabilityType.PROXY, proxy);


            driver = new ChromeDriver(desiredCapabilities);


            driver.get(baseUrl);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The proxy setting has been added with desired capabilities to pass values to proxy authentication,worked finally

Minivet answered 2/8, 2017 at 15:6 Comment(2)
@AndreyP is your project using resources using internet css file, js ?Minivet
What about for http authentification?Chrysalid
S
3

I know this is an old thread, still leaving a solution which worked for me using browsermob proxy, for someone who still needs an option.

Maven dependency:

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.0.0</version>
</dependency>
<dependency>
    <groupId>net.lightbody.bmp</groupId>
    <artifactId>browsermob-core</artifactId>
    <version>2.1.5</version>
</dependency>

Java Code:

// I am using firefox
System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\geckodriver.exe");

BrowserMobProxy browsermobProxy = new BrowserMobProxyServer();
browsermobProxy.setChainedProxy(new InetSocketAddress(PROXY_HOSTNAME, PROXY_PORT));
browsermobProxy.chainedProxyAuthorization(PROXY_USERNAME, PROXY_PASSWORD, AuthType.BASIC);
browsermobProxy.start(0);

FirefoxBinary firefoxBinary = new FirefoxBinary();
FirefoxOptions firefoxOptions = new FirefoxOptions();

firefoxOptions.setBinary(firefoxBinary );
firefoxOptions.setProfile(firefoxProfile);

firefoxOptions.setProxy(ClientUtil.createSeleniumProxy(browsermobProxy));

WebDriver webDriverWithProxy = new FirefoxDriver(firefoxOptionsWithProxy);

webDriverWithProxy.get("https://stackoverflow.com/");
Sladen answered 21/11, 2021 at 18:2 Comment(0)
P
2

This code (from Avishka Perera's answer) does not work for me:

    proxy.setSocksUsername("avishka");
    proxy.setSocksPassword("12345678");

The username and password set in this way do not take effect for the http/https proxy - the Proxy Authentication box still popped up.

I'm using Selenium java 3.141.0, ChromeDriver 2.33 and chrome 70. What works for me is to follow Mike's answer here Selenium using Python: enter/provide http proxy password for firefox . Create the zip file, then add the extension like this:

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addExtensions(new File("src/test/resources/proxy.zip"));
WebDriver driver = new ChromeDriver(chromeOptions);

One catch is that the above code will run into error if you set "--headless" argument because chrome in headless mode cannot have extension (Is it possible to run Google Chrome in headless mode with extensions?). If your Chrome runs in Docker container and cannot show the UI, then to get this solution work, you'll need to run with Xvfb instead of in headless mode.

Postmaster answered 18/12, 2018 at 22:35 Comment(0)
H
2

Simple method to add authenticated proxy using selenium wire in Both firefox and chrome

In python

Step:1

pip3 install selenium-wire

Step:2

from seleniumwire import webdriver
from selenium import webdriver

step:3

Add proxy in below-mensioned format

proxy= "username:password@ip:port"
        options = {'proxy': {'http': proxy, 'https': proxy, 'no_proxy': 'localhost,127.0.0.1,dev_server:8080'}}

step:4 pass proxy as an argument

CHROME

driver = webdriver.Chrome(options=chrome_options, executable_path="path of chrome driver", seleniumwire_options=options)

Firefox

driver = webdriver.Firefox(seleniumwire_options=options, executable_path="path of firefox driver", options=firefox_options)

step:5 Verify proxy applied by requesting the url https://whatismyipaddress.com/

time.sleep(20)
driver.get("https://whatismyipaddress.com/")

Note: But selenium log shows it runs in without proxy because we are using an external package to apply proxy.

Hers answered 2/2, 2020 at 16:33 Comment(0)
C
1

It took me very-very much time! It is possible with selenium 4, the driver.register closes the window:

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--user-agent=" + userAgent);
chromeOptions.addArguments("--proxy-server=http://" + ipAddress.getHost() + ":" + ipAddress.getPort());
chromeOptions.addArguments("--headless");

ChromeDriver driver = new ChromeDriver(chromeOptions);

// !! the solution, call after new Driver:
driver.register(UsernameAndPassword.of(ipAddress.getUsername(), ipAddress.getPassword()));

P.S. Have tested on:

  • Java openjdk 17.0.8 2023-07-18-
  • Selenium 4.10.0
  • Ubuntu 22.04.3 LTS
  • Chromedriver linux64 114.0.5735.90
  • Google Chrome 114.0.5735.90
Catenane answered 18/8, 2023 at 12:42 Comment(0)
K
0

The approach that worked perfectly fine for me is by using AutoIT.

Install autoIT and prepare a simple script as shown in the picture attached and execute the script file from your testscript using Runtime.getRuntime().exec("\YOUR_SCRIPT.exe") before navigating to the baseURL.

Kolivas answered 6/3, 2019 at 19:31 Comment(1)
Try running the automation in a different resolutions. AutoIT fails to identify the required fields.Minivet

© 2022 - 2024 — McMap. All rights reserved.