How to handle Authentication pop up in Safari using Selenium? - selenium-webdriver

I have been having issues with Safari 11 using WebDriver. I was able to bypass that authentication popup by using the following:
String URL = "http://" + username + ":" + password + "#" + Settings.AUT;
Driver.Navigate().GoToUrl(URL + "/");
This somehow worked with Safari 10, though I upgraded my Safari to 11 due to the maximize window is not working with Safari 10.
I am currently using webdriver 2.48 for safari.
I have no idea anymore on what to do with Safari tests. Is this a known issue? I know there is AutoIT but is there any other way to do this?

It is possible that your current web driver doesn't work with that version of browser.
SafariDriver - DEPRECATED - use Apple's SafariDriver with Safari 10+
SafariDriver now requires manual installation of the extension prior
to automation
From:
http://www.seleniumhq.org/download/

According to the RFC 3986 this format of passing the user name and password in the URL is deprecated and while it still works in Chrome and FF, Safari does not support this anymore.

You can use AppleScript and Java to handle the browser pop-up. Here is the Java code to execute AppleScript, just call this function and pass the AppleScript as String:
public static void execute(String appleScript)
{
Process process = null;
try
{
String[] args = { "osascript", "-e", appleScript };
process = Runtime.getRuntime().exec(args);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String logs = null;
while ((logs = bufferedReader.readLine()) != null)
{
System.out.println(logs);
}
}
catch (Exception e)
{
}
finally
{
if (process != null)
process.destroy();
}
}
If you don't know how to write AppleScript go to their tutorials.
Also, to check you have given access permission to System Events; go to 'System Preferences > Security & Privacy > Privacy > Accessibility' and make sure you have 'Eclipse' and 'System Events' checked.

Related

How to give option to user for choosing the file folder in xamarin forms?

I would like to give user an ability to chose the desired file location in his/her device to save information.
I didn't find anything on the Internet that would work for all the platforms. The only options seem to be available for Android.
You can use the package Xamarin.Plugin.FilePicker from NuGet. It is a FilePicker Plugin for Xamarin.Forms.
Example:
try
{
FileData fileData = await CrossFilePicker.Current.PickFile();
if (fileData == null)
return; // user canceled file picking
string fileName = fileData.FileName;
string contents = System.Text.Encoding.UTF8.GetString(fileData.DataArray);
System.Console.WriteLine("File name chosen: " + fileName);
System.Console.WriteLine("File data: " + contents);
}
catch (Exception ex)
{
System.Console.WriteLine("Exception choosing file: " + ex.ToString());
}
For iOS ,you need to Configure iCloud Driver for your app.For more detail and if you want download a sample you can refer here.
For IOS you can read this document.
https://possiblemobile.com/2013/04/using-xcode-to-test-location-services/
All,( android and IOS ) can be manipulated by dependency injection. So you are using native code of android and of IOS and choose/control in xamarin forms.
Good luck
Guilherme

cookies validation using selenium

I am new to selenium. Actually I am working on some cookie validation project, which requires me to manually check the cookies present before and after clicking on some consent link in multiple browsers (Firefox, ie, chrome, safari).
Previously in the phase 1 project I ran a qtp script to treat the firefox as a window object and capture screenshots, but that is quite troublesome if the resolution changes or any minor look-n-feel changes. Also it is quite difficult to manage and it works on firefox only and I needed to write the same script again for chrome and safari. Apart from this since QTP is licensed product and currently we are using seat license so I can't run it on multiple machines to speed up execution.
So I thought moving to Selenium. As of now my requirement is:
1. open the page - take the screenshot once page loaded.
2. check the cookies using firebug or any other way - take the screenshot
3. click the link to close the consent - take screenshot once consent closed.
4. refresh the page and again check the cookies using firebug - take screenshot
So I done some research on selenium and found that I can validate the cookies using verifyCookie but still I need screenshot of firebug window for cookies. So I got stuck here.
please help me out here..
I found some possible way to do this on Firefox but now I was looking forward for something similar for Chrome if that possible. Thanks
Selenium cannot interact with firefox extensions, or the browser in the way you want it to.
What you can do is collect a list of cookies on the page by doing:
driver.manage().getCookies()
This will give you a list of all cookies that are visible to Selenium. Please note that this is the same as the cookies that are visible in the JavaScript console (Not all cookies are visible via JavaScript, for example cookies set with the HTTPOnly attribute) using:
document.cookie
I would suggest you use getCookies() to programatically validate the cookies.
In selenium IDE if you want to take screenshot of the page use captureEntirePageScreenshot command
captureEntirePageScreenshot | D:\\test.png |
D:\\test.png - path of file where you want to save the file
Got some solution
public class Selenium1st {
/**
* #param args
*/
public static void main(String[] args) throws IOException, AWTException{
// TODO Auto-generated method stub
System.setProperty("webdriver.firefox.bin","C:\\Program Files (x86)\\Mozilla Firefox\\Firefox.exe");
FirefoxProfile firefoxProfile = new FirefoxProfile();
String domain = "extensions.firebug.";
firefoxProfile.setPreference("app.update.enabled", false);
firefoxProfile.addExtension(new File("E:\\softs\\selenium-2.29.0\\firebug\\firebug-1.11.2-fx.xpi"));
firefoxProfile.setPreference(domain + "currentVersion", "1.11.2");
firefoxProfile.setPreference("extensions.firebug.cookies.enableSites", true);
firefoxProfile.setPreference("extensions.firebug.allPagesActivation", "on");
firefoxProfile.setPreference(domain + "framePosition", "bottom");
firefoxProfile.setPreference(domain + "defaultPanelName", "cookies");
WebDriver driver = new FirefoxDriver(firefoxProfile);
driver.get("http://www.google.com/webhp?complete=1&hl=en");
WebElement query = driver.findElement(By.name("q"));
query.sendKeys("Cheese");
query.sendKeys("\n");
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(new Dimension(1024, 768)));
File path = new File("E:\\abc");//Path to your file
if(path.getName().indexOf(".jpg") == -1){
path = new File(path.getPath() + ".jpg");
}
ImageIO.write(img, "jpg", path);
}
}
might be useful.

How to handle login pop up window using Selenium WebDriver?

How to handle the login pop up window using Selenium Webdriver? I have attached the sample screen here. How can I enter/input Username and Password to this login pop up/alert window?
Thanks & Regards,
Use the approach where you send username and password in URL Request:
http://username:password#the-site.com
So just to make it more clear. The username is username password is password and the rest is usual URL of your test web
Works for me without needing any tweaks.
Sample Java code:
public static final String TEST_ENVIRONMENT = "the-site.com";
private WebDriver driver;
public void login(String uname, String pwd){
String URL = "http://" + uname + ":" + pwd + "#" + TEST_ENVIRONMENT;
driver.get(URL);
}
#Test
public void testLogin(){
driver = new FirefoxDriver();
login("Pavel", "UltraSecretPassword");
//Assert...
}
This should works with windows server 2012 and IE.
var alert = driver.SwitchTo().Alert();
alert.SetAuthenticationCredentials("username", "password");
alert.Accept();
This is very simple in WebDriver 3.0(As of now it is in Beta).
Alert alert = driver.switchTo().alert() ;
alert.authenticateUsing(new UserAndPassword(_user_name,_password));
driver.switchTo().defaultContent() ;
Hopefully this helps.
Now in 2020 Selenium 4 supports authenticating using Basic and Digest auth . Its using the CDP and currently only supports chromium-derived browsers
Example :
Java Example :
Webdriver driver = new ChromeDriver();
((HasAuthentication) driver).register(UsernameAndPassword.of("username", "pass"));
driver.get("http://sitewithauth");
Note : In Alpha-7 there is bug where it send username for both user/password. Need to wait for next release of selenium version as fix is available in trunk https://github.com/SeleniumHQ/selenium/commit/4917444886ba16a033a81a2a9676c9267c472894
Solution: Windows active directory authentication using Thread and Robot
I used Java Thread and Robot with Selenium webdriver to automate windows active directory authentication process of our website.
This logic worked fine in Firefox and Chrome but it didn't work in IE. For some reason IE kills the webdriver when authentication window pops up whereas Chrome and Firefox prevents the web driver from getting killed. I didn't try in other web browser such as Safari.
//...
//Note: this logic works in Chrome and Firefox. It did not work in IE and I did not try Safari.
//...
//import relevant packages here
public class TestDemo {
static WebDriver driver;
public static void main(String[] args) {
//setup web driver
System.setProperty("webdriver.chrome.driver", "path to your chromedriver.exe");
driver = new ChromeDriver();
//create new thread for interaction with windows authentication window
(new Thread(new LoginWindow())).start();
//open your url. this will prompt you for windows authentication
driver.get("your url");
//add test scripts below ...
driver.findElement(By.linkText("Home")).click();
//.....
//.....
}
//inner class for Login thread
public class LoginWindow implements Runnable {
#Override
public void run() {
try {
login();
} catch (Exception ex) {
System.out.println("Error in Login Thread: " + ex.getMessage());
}
}
public void login() throws Exception {
//wait - increase this wait period if required
Thread.sleep(5000);
//create robot for keyboard operations
Robot rb = new Robot();
//Enter user name by ctrl-v
StringSelection username = new StringSelection("username");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(username, null);
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);
//tab to password entry field
rb.keyPress(KeyEvent.VK_TAB);
rb.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(2000);
//Enter password by ctrl-v
StringSelection pwd = new StringSelection("password");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(pwd, null);
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);
//press enter
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
//wait
Thread.sleep(5000);
}
}
}
The easiest way to handle the Authentication Pop up is to enter the Credentials in Url Itself. For Example, I have Credentials like Username: admin and Password: admin:
WebDriver driver = new ChromeDriver();
driver.get("https://admin:admin#your website url");
This is a solution for Python based selenium, after going through the source code (here).
I found this 3 steps as useful.
obj = driver.switch_to.alert
obj.send_keys(keysToSend="username\ue004password")
obj.accept()
Here \ue004 is the value for TAB which you can find in Keys class in the source code.
I guess the same approach can be used in JAVA as well but not sure.
My usecase is:
Navigate to webapp.
Webapp detects I am not logged in, and redirects to an SSO site - different server!
SSO site (maybe on Jenkins) detects I am not logged into AD, and shows a login popup.
After you enter credentials, you are redirected back to webapp.
I am on later versions of Selenium 3, and the login popup is not detected with driver.switchTo().alert(); - results in NoAlertPresentException.
Just providing username:password in the URL is not propagated from step 1 to 2 above.
My workaround:
import org.apache.http.client.utils.URIBuilder;
driver.get(...webapp_location...);
wait.until(ExpectedConditions.urlContains(...sso_server...));
URIBuilder uri = null;
try {
uri = new URIBuilder(driver.getCurrentUrl());
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
uri.setUserInfo(username, password);
driver.navigate().to(uri.toString());
You can use this Autoit script to handle the login popup:
WinWaitActive("Authentication Required","","10")
If WinExists("Authentication Required") Then
Send("username{TAB}")
Send("Password{Enter}")
EndIf'
I was getting windows security alert whenever my application was opening. to resolve this issue i used following procedure
import org.openqa.selenium.security.UserAndPassword;
UserAndPassword UP = new UserAndPassword("userName","Password");
driver.switchTo().alert().authenticateUsing(UP);
this resolved my issue of logging into application. I hope this might help who are all looking for authenticating windows security alert.
Simply switch to alert and use authenticateUsing to set usename and password and then comeback to parent window
Alert Windowalert = driver.switchTo().alert() ;
Windowalert.authenticateUsing(new UserAndPassword(_user_name,_password));
driver.switchTo().defaultContent() ;
1 way to handle this you can provide login details with url. e.g. if your url is "http://localhost:4040" and it's asking "Username" and "Password" on alert prompt message then you can pass baseurl as "http://username:password#localhost:4040".
Hope it works
In C# Selenium Web Driver I have managed to get it working with the following code:
var alert = TestDriver.SwitchTo().Alert();
alert.SendKeys(CurrentTestingConfiguration.Configuration.BasicAuthUser + Keys.Tab + CurrentTestingConfiguration.Configuration.BasicAuthPassword);
alert.Accept();
Although it seems similar, the following did not work with Firefox (Keys.Tab resets all the form and the password will be written within the user field):
alert.SendKeys(CurrentTestingConfiguration.Configuration.BasicAuthUser);
alert.SendKeys(Keys.Tab);
alert.SendKeys(CurrentTestingConfiguration.Configuration.BasicAuthPassword);
Also, I have tried the following solution which resulted in exception:
var alert = TestDriver.SwitchTo().Alert();
alert.SetAuthenticationCredentials(
CurrentTestingConfiguration.Configuration.BasicAuthUser,
CurrentTestingConfiguration.Configuration.BasicAuthPassword);
System.NotImplementedException: 'POST
/session/38146c7c-cd1a-42d8-9aa7-1ac6837e64f6/alert/credentials did
not match a known command'
Types of popups are defined in webdriver alerts: https://www.selenium.dev/documentation/webdriver/browser/alerts/
Here it is another type - authentication popup - eg generated by Weblogic and not seen by Selenium.
Being HTTPS the user/pass can't be put directly in the URL.
The solution is to create a browser extension: packed or unpacked.
Here is the code for unpacked and the packing procedure: https://qatestautomation.com/2019/11/11/handle-authentication-popup-in-chrome-with-selenium-webdriver-using-java/
In manifest.json instead of “https://ReplaceYourCompanyUrl“ put “<all_urls>”.
Unpacked can be used directly in Selenium:
#python:
co=webdriver.ChromeOptions()
co.add_argument("load-extension=ExtensionFolder")
<all_urls> is a match pattern
The flow for requests is in https://developer.chrome.com/docs/extensions/reference/webRequest/
We can also update browser setting to consider logged in user -
Internet Options-> Security -> Security Settings-> Select Automatic login with current user name and password.
The following Selenium-Webdriver Java code should work well to handle the alert/pop up up window:
driver.switchTo().alert();
//Selenium-WebDriver Java Code for entering Username & Password as below:
driver.findElement(By.id("userID")).sendKeys("userName");
driver.findElement(By.id("password")).sendKeys("myPassword");
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
I used IE, then create code like that and works after modification several code:
public class TestIEBrowser {
public static void main(String[] args) throws Exception {
//Set path of IEDriverServer.exe.
// Note : IEDriverServer.exe should be In D: drive.
System.setProperty("webdriver.ie.driver", "path /IEDriverServer.exe");
// Initialize InternetExplorerDriver Instance.
WebDriver driver = new InternetExplorerDriver();
// Load sample calc test URL.
driver.get("http://... /");
//Code to handle Basic Browser Authentication in Selenium.
Alert aa = driver.switchTo().alert();
Robot a = new Robot();
aa.sendKeys("host"+"\\"+"user");
a.keyPress(KeyEvent.VK_TAB);
a.keyRelease(KeyEvent.VK_TAB);
a.keyRelease(KeyEvent.VK_ADD);
setClipboardData("password");
a.keyPress(KeyEvent.VK_CONTROL);
a.keyPress(KeyEvent.VK_V);
a.keyRelease(KeyEvent.VK_V);
a.keyRelease(KeyEvent.VK_CONTROL);
//Thread.sleep(5000);
aa.accept();
}
private static void setClipboardData(String string) {
// TODO Auto-generated method stub
StringSelection stringSelection = new StringSelection(string); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
}

Is it possible to launch a Silverlight 4 OOB application from a web page? [duplicate]

This question already has an answer here:
Launch Silverlight Out-of-Browser from browser post-installation
(1 answer)
Closed 2 years ago.
I'm planning to build a download manager application and would like to be able to launch the application when a user clicks a button the site. The application would obviously already need to be installed on the client machine.
There are a few reasons why this needs to be written using Silverlight, but they're not really relevant to the question. I only mention it so that people don't suggest that I use another technology.
Doing a bit of a mash up from two other posts [1] and [2].
But of course this will only work for Windows not Mac. There you will have to fallback to the #michael-s-scherotter style solution.
private void Button_Click(object sender, RoutedEventArgs e)
{
if (Application.Current.HasElevatedPermissions && System.Windows.Interop.ComAutomationFactory.IsAvailable)
{
string run = "\""%ProgramFiles%\\Microsoft Silverlight\\sllauncher.exe"\" /emulate:"Silverface.xap" /origin:\"http://www.silverlight.net/content/samples/apps/facebookclient/ClientBin/Silverface.xap\" /overwrite";
dynamic cmd = ComAutomationFactory.CreateObject("WScript.Shell");
cmd.Run(run, 1, true);
}
}
Yes. Here is an example:
http://www.silverlight.net/content/samples/apps/facebookclient/sfcquickinstall.aspx
I found a trick that launches the installed silverlight OOB from the silverlight app in-browser. Both applications should be singed and have the elevated trust.
When a user installs the silverlight OOB App first time, retrive the path and argument values from the shortcut file of the OOB app on desktop. (ref: How I can use Shell32.dll in Silverlight OOB) If you know the the path and argument values, you can launch the OOB app using Com Object.
Send the retrive the path and argument values to the silverlight App in-browser. (ref: http://msdn.microsoft.com/en-us/library/dd833063(v=vs.95).aspx)
Store the path and argument values in a cookie.
Now, the silverlight app in-browser is able to launch the silverlight OOB using the path and argument values in the cookie.
using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
{
shell.Run(launchPath);
}
I hope this trick is useful to you :)
It is possible if you agree to install the app each time the user clicks on it.
You also should set the app to require elevated trust in its OOB settings.
Just uninstall the app on startup (for example, in main window constructor):
if (Application.Current.HasElevatedPermissions && Application.Current.InstallState == InstallState.Installed)
{
string launcherPath = string.Empty;
using (dynamic shell = AutomationFactory.CreateObject("Shell.Application"))
{
string launcher64 = #"C:\Program Files (x86)\Microsoft Silverlight";
string launcher32 = #"C:\Program Files\Microsoft Silverlight";
dynamic folder64 = shell.NameSpace(launcher64);
if (folder64 != null)
{
launcherPath = launcher64;
}
else
{
dynamic folder32 = shell.NameSpace(launcher32);
if (folder32 != null)
{
launcherPath = launcher32;
}
}
}
using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
{
var origin = Application.Current.Host.Source.OriginalString;
var launchCmd = string.Format(#"""{0}\sllauncher.exe"" /uninstall /origin:""{1}""", launcherPath, origin);
shell.Run(launchCmd);
}
}
(the code for uninstall was taken from this post: http://www.wintellect.com/blogs/sloscialo/programmatically-uninstalling-silverlight-out-of-browser-application)

Generating RDP file on the fly

I want to create a web application similar to TS Web Access, where I can create rdp files on the fly for Remote Apps configured on the server. Any idea??
We had to do this exact thing.
private void InvokeRDPSign(String fileName, String certificateThumbPrint)
{
Process signingProcess = new Process();
signingProcess.StartInfo.FileName = #"rdpsign.exe";
String arguments = String.Format("/sha1 {0} {1}", certificateThumbPrint, fileName);
signingProcess.StartInfo.Arguments = arguments;
signingProcess.StartInfo.UseShellExecute = false;
signingProcess.StartInfo.RedirectStandardOutput = true;
signingProcess.StartInfo.WorkingDirectory = Environment.SystemDirectory;
signingProcess.Start();
String signingOutput = signingProcess.StandardOutput.ReadToEnd();
signingProcess.WaitForExit();
int exitCode = signingProcess.ExitCode;
//TODO: should we throw an error if the exitcode is not 0
}
Be aware that that the RDPSign.exe is different on each version of windows. You will find that an older version of the utility will ignore newer settings from the signature.
well Having looked at a 'rdp' file this is the contents:
screen mode id:i:2
desktopwidth:i:1280
desktopheight:i:768
session bpp:i:32
winposstr:s:2,3,1430,104,2230,704
compression:i:1
keyboardhook:i:2
displayconnectionbar:i:1
disable wallpaper:i:1
disable full window drag:i:1
allow desktop composition:i:0
allow font smoothing:i:0
disable menu anims:i:1
disable themes:i:0
disable cursor setting:i:0
bitmapcachepersistenable:i:1
full address:s: [YOUR IP]
audiomode:i:0
redirectprinters:i:1
redirectcomports:i:0
redirectsmartcards:i:1
redirectclipboard:i:1
redirectposdevices:i:0
autoreconnection enabled:i:1
authentication level:i:0
prompt for credentials:i:0
negotiate security layer:i:1
remoteapplicationmode:i:0
alternate shell:s:
shell working directory:s:
gatewayhostname:s:
gatewayusagemethod:i:4
gatewaycredentialssource:i:4
gatewayprofileusagemethod:i:0
promptcredentialonce:i:1
drivestoredirect:s:
Just create that as a string, seems straightforward.
ps I have no idea what the 'winposstr' parameter is...

Resources