Using Selenium on https web application that runs over vpn - java

First of all, I need to state that I am total beginner with Selenium.
I am trying to test an application in firefox browser using Selenium. Due to security issues the application works only over vpn.
My problem occurs with the following steps; I create the webdriver and navigate to the start (login) page of application. I get an "Authorization request" popup. If I cancel the popup, then I get to a page that states "Connection is not secure" (it's https address). After I get passed that, I lose the part where Selenium program should populate username and password and it just stays on the login page.
My question, is there a way to start Selenium testing on an application so that it is already opened and prepared (ie logged in) in browser? I am not happy that username and password are hard-coded in Selenium code.
If that is not possible, how do I skip that authorization popup and problem with non-secure connection? How do I populate username and password in safest way?
Thanks!
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Selenium-java-3.0.1\\geckodriver.exe");
// I tried also with this code bellow in comment, but it did not work, it did not even get to login page
//WebDriverWait wait = new WebDriverWait(driver, 10);
//Alert alert = wait.until(ExpectedConditions.alertIsPresent());
//alert.authenticateUsing(new UserAndPassword("cfadmin", "20lipim18"));
driver.get("https://Application_login_page.com");
driver.findElement(By.xpath(".//*[#id='login']")).click();
driver.findElement(By.xpath("[#id='login']")).sendKeys("Username");
}

if it's possible, is there a way to start Selenium testing on application that is already opened and prepared (logged) in browser?
Try using firefox profile. Since selenium open fresh instance of browser by default. You can use your own firefox frofile.
This is a code to implement a profile, which can be embedded in the selenium code.
ProfilesIni profile = new ProfilesIni();
// this will create an object for the Firefox profile
FirefoxProfile myprofile = profile.getProfile("default");
// this will Initialize the Firefox driver
WebDriver driver = new FirefoxDriver(myprofile)
It will also maintain the session means you are already login to the application in firefox(default profile). Then if you execute the script, you will see that you are already logged in to the application.

There is no way to open already authorised page, you have to have to pass username and password through selenium script.
You may use below code to do the authentication
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));

Related

Cant login even i am typing manually while selenium listen browser

im trying to web scrapping with selenium library in my java project. While i am try to login site with interactive behaviour (manually type username and password in login page) cant login. Site is under recaptcha protection, i think block login operation, because if i dont listen with browser with selenium, i can login.
Code;
//Webdriver
System.setProperty("webdriver.chrome.driver", "data/src/main/kotlin/com/myapp/data/drivers/chromedriver.exe");
WebDriverManager.chromedriver().setup()
//Chrome Options
val options = ChromeOptions()
// Fixing 255 Error crashes
options.addArguments("--no-sandbox")
options.addArguments("--disable-dev-shm-usage")
// Options to trick bot detection -> i can trick bot detection with this code. Site ban me if dont use this lines
options.addArguments("--disable-blink-features=AutomationControlled")
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"))
options.setExperimentalOption("useAutomationExtension", false)
options.addArguments("window-size=1920,1080")
options.addArguments("disable-infobars")
options.addArguments("user-data-dir=/tmp/afabc")
// Changing the user agent
val userAgent = UserAgent(RandomUserAgent().getRandomUserAgent())
options.addArguments("user-agent=${userAgent}")
//Chrome Driver
val driver: WebDriver = ChromeDriver(options)
driver.manage().window().position = Point(0,0)
//Wait For Element
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000))
val wait = WebDriverWait(driver,60)
//Operation
driver.get(LOGIN_SITE_URL)
val afterLoginPageSomeElementXpath = "/html/body/div[1]/div[1]/div[5]/ul/li[1]/a"
//For Listen user can login or not // İf i remove this code, i can login.
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(afterLoginPageSomeElementXpath)))
How can i bypass this issue? Anyone help?

How can I test a "Remember Me" checkbox feature in Selenium

I'm trying to test the "Remember Me" functionality of a login form. I'm able to type in the user name and password, click the checkbox, click submit, and quit() or close() the browser. But when I reopen the browser with new ChromeDriver() (or any other WebDriver implementation), the test site does not remember anything because all cookies are deleted when the browser is closed and cannot be accessed when the browser is reopened.
For Chrome (config):
You have to set the path to user-dir which will save all the login info after you login for the first time. The next time you login again, login info from the user-dir will be taken.
System.setProperty("webdriver.chrome.driver", "res/chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("user-data-dir=D:/temp/");
capabilities.setCapability("chrome.binary","res/chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY,options);
WebDriver driver = new ChromeDriver(capabilities);
Login for the first time:
driver.get("https://gmail.com");
//Your login script typing username password, check 'keep me signed in' and so on
Close the driver (do NOT quit):
driver.close();
Re-initialize the driver and navigate to the site. You should not be asked for username and password again:
driver = new ChromeDriver(capabilities);
driver.get("http://gmail.com");
The above can be implemented for firefox using a firefox profile.
If the "Remember Me" feature is implemented using persistent cookies (I doubt that there is any other way to implement it), then you can actually test the feature in a cross-browser compatible way by programmatically manipulating the cookies. Cookies with an expiration date (or Expiry in the Selenium API) are persistent cookies and are stored when the browser is closed and retrieved when the browser is re-opened. Non-persistent cookies are not stored when the browser is closed. With this information, we can simulate what should happen when the browser closes, by programmatically deleting all non-persistent cookies:
// Check the "Remember Me" checkbox and login here.
Set<Cookies> cookies = webDriver.manage().getCookies();
for (Cookie cookie : cookies) {
// Simulate a browser restart by removing all non-persistent cookies.
if (cookie.getExpiry() == null) {
webDriver.manage().deleteCookie(cookie);
}
}
// Reload the login page.
webDriver.get(currentLoginPageURL);
// Assert that some text like "You are logged in as..." appears on the page to
// indicate that you are still logged in.

Webdriver - HTTP authentication dialog

I have a very simple selenium-webdriver script. I would like to do HTTP authentication using webdriver.
Script:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.httpwatch.com/httpgallery/authentication/");
driver.findElement(By.id("displayImage")).click();
Thread.sleep(2000);
driver.switchTo().alert().sendKeys("httpwatch");
Issue:
driver.switchTo().alert().sendKeys("httpwatch");
throws
org.openqa.selenium.NoAlertPresentException: No alert is present
Question:
Does Webdriver find only an alert dialog as alert?
What are my options to automate this without using AutoIt OR http:// username:password #somesite
EDIT
Alert has below method and does not seem to have been implemented yet.
driver.switchTo().alert().authenticateUsing(new UsernameAndPassword("username","password"))
The problem is that this is not a javascript popup hence you cannot manipulate it via selenium's alert().
If both AutoIt and submitting credentials in the URL (the easiest option - just open up the url and click "Display Image") are not options for you, another approach could be to use AutoAuth firefox addon to automatically submit the previously saved credentials:
AutoAuth automatically submits HTTP authentication dialogs when you’ve
chosen to have the browser save your login information. (If you’ve
already told the browser what your username and password are, and
you’ve told it to remember that username and password, why not just
have it automatically submit it instead of asking you each time?)
Following the answer suggested in HTTP Basic Auth via URL in Firefox does not work? thread:
Install AutoAuth Firefox plugin;
Visit the site where the authentication is needed. Enter your username and password and make sure to choose to save the credentials;
Save AutoAuth installation file at your hard drive: at the plugin page, right click at “Add to Firefox” and “Save link as”;
Instantiate Firefox webdriver as following:
FirefoxProfile firefoxProfile = new ProfilesIni().getProfile("default");
File pluginAutoAuth = new File("src/test/resources/autoauth-2.1-fx+fn.xpi");
firefoxProfile.addExtension(pluginAutoAuth);
driver = new FirefoxDriver(firefoxProfile);
Also, in a way similar to AutoIt option - you can use sikuli screen recognition and automation tool to submit the credentials in the popup.
Also see other ideas and options:
Support BASIC and Digest HTTP authentication
Handling browser level authentication using Selenium
The Basic/NTLM authentication pop-up is a browser dialog window. WebDriver (Selenium 2.0) cannot interact with such dialog windows. The reason for this is because WebDriver aims solely at mimicking user interaction with websites, and browser dialog windows are currently not in that scope. JavaScript dialog windows, are part of the website, so WebDriver can handle those. In Selenium 1.0 it is possible to do basic authentication.
So how to solve this issue? 1) Authentication via URL http://username:password#website.com 2) Use a browser plugin that will handle the Basic/NTLM autentication 3) Use a local proxy that will modify the request header and pass along the username/password and 4) Make use of a robot, like AutoIt, or some Java library.
Option 1: is the easiest and has the least impact on the system/test. Option 2: has a high browser impact as your loading plugins. Also every browser uses its own plugin and it's possible that the required plugin for a certain browser is not available. Option 3: Works well with HTTP, but HTTPS requires custom certicates thus not always an option. Not much impact on both system and test. Option 4: Mimics keyboard presses, its a go to solution but prone to errors. Only works when the dialog window has focus and it is possible that this is not always the case.
I faced same issue, and got some concrete solution using robot class. Its workaround or solution, Let see , but it works.
public class DialogWindow implements Runnable {
#Override
public void run() {
try {
entercredentials();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void entercredentials() InterruptedException {
Thread.sleep(5000);
try {
enterText("username");
enterSpecialChar(KeyEvent.VK_TAB);
enterText("password");
enterSpecialChar(KeyEvent.VK_ENTER);
} catch (AWTException e) {
}
}
private void enterText(String text) throws AWTException {
Robot robot = new Robot();
byte[] bytes = text.getBytes();
for (byte b : bytes) {
int bytecode = b;
// keycode only handles [A-Z] (which is ASCII decimal [65-90])
if (bytecode> 96 && bytecode< 123)
bytecode = bytecode - 32;
robot.delay(40);
robot.keyPress(bytecode);
robot.keyRelease(bytecode);
}
}
private void enterSpecialChar(int s) throws AWTException {
Robot robot = new Robot();
robot.delay(40);
robot.keyPress(s);
robot.keyRelease(s);
}
}
How to call it
WebDriver driver= new FirefoxDriver()// or any other driver with capabilities and other required stuff
(new Thread(new DialogWindow())).start();
driver.get(url);

Selenium Webdriver Continuing After Site from get() Prompts for Cert

I'm writing a Java app in which I'm doing a simple driver.get(url) in which the url will prompt for a cert selection. I want to try and automate the cert selection process in Firefox 33 using the AutoIt jar, but I can't even get my Java program to continue after it executes this get, since the site is in an indefinite state of loading until a cert is selected, so the execution indefinitely stays on the get itself. Is there any way around this?
I found a similar question: Make Selenium Webdriver Stop Loading the page if the desired element is already loaded?
Ths solution given in the above link is to change the firefox settings in case the webpage is taking too long to load.
FirefoxBinary firefox = new FirefoxBinary(new File("/path/to/firefox.exe"));
FirefoxProfile customProfile = new FirefoxProfile();
customProfile.setPreference("network.http.connection-timeout", 10);
customProfile.setPreference("network.http.connection-retry-timeout", 10);
driver = new FirefoxDriver(firefox, customProfile);

Selenium Webdriver - Chrome - Switch Window and back - Unable to receive message from renderer

This is my first question on Stack Overflow. Thanks to all StackOverflow users who keeps technology passion ticking.
I am testing a web application with selenium Webdriver . It is payment webpage where, after selecting Payment method as 'PayPal' it opens up a new Popup , a PayPal popup and i Switch window to Paypal , do all my necessary Transaction. And once the Transaction is successful , automatically the paypal popup is closed, and i am not able to return to my original window from where i have initiated transaction.
I am getting following error in eclipse console:
Starting ChromeDriver (v2.9.248315) on port 25947
[70.164][SEVERE]: Unable to receive message from renderer
The following details might help :
selenium Webdriver (2.28.0)
java - JRE7
Google Chrome Version - Version 33.0.1750.146
Test Framework - Test NG
Here is my code :
// To Switch to Popup/Paypal window
String currentWindowHandle=driver.getWindowHandle();
Set<String> openWindowsList=driver.getWindowHandles();
String popUpWindowHandle=null;
for(String windowHandle:openWindowsList)
{
if (!windowHandle.equals(currentWindowHandle))
popUpWindowHandle=windowHandle;
}
driver.switchTo().window(popUpWindowHandle);
// Carraying out my paypal transaction
driver.manage().window().maximize();
driver.findElement(By.xpath("//*[#id='loadLogin']")).click();
Thread.sleep(8000);
WebElement login_email = driver.findElement(By.xpath("//*[#id='login_email']"));
login_email.clear();
login_email.sendKeys(Keys.BACK_SPACE);
login_email.sendKeys("abc#abc.com");
WebElement login_password = driver.findElement(By.xpath("//*[#id='login_password']"));
login_password.clear();
login_password.sendKeys("abcxyz");
// Next Click is Final Click on PayPal
driver.findElement(By.xpath("//*[#id='submitLogin']")).click();
// Transaction is finished on PayPal side and it automatically popup is closed
//Now i am trying to switch to my last working(original) window
driver.switchTo().window("My Web Page Title");
You should be using:
driver.switchTo().window(currentWindowHandle);
It causes because page took long time to load , you need add additional line to your chromedriver option.
System.setProperty("webdriver.chrome.driver","E:\\selenium\\chromedriver_2.41\\chromedriver.exe");
//mention the below chrome option to solve timeout exception issue
ChromeOptions options = new ChromeOptions();
options.setPageLoadStrategy(PageLoadStrategy.NONE);
// Instantiate the chrome driver
driver = new ChromeDriver(options);
The problem is resolved.
The place where I was declaring currentWindowHandle was after clicking and it takes the new window as the Current Window handle.
I just moved below statement to before the new window click event.
String currentWindowHandle=driver.getWindowHandle();
Thanks all for your time and Help.

Categories