How to Handle Authentication alert of browser in selenium webdriver?

南楼画角 提交于 2020-01-15 11:05:05

问题


Can anyone know that how can we handle Authenticate alert box of browser in selenium Webdriver ?

I user following code but its not working.

driver.switchTo().alert().authenticateUsing(new UserAndPassword("uname", "Password"));

Here is a screenshot of what I am trying to fill in:

Does anyone know how can I enter those credentials?


回答1:


Something like this?

driver.Navigate().to("http://UserName:Password@url.‌​com")

or

WebDriverWait wait = new WebDriverWait(driver, 10);      
Alert alert = wait.until(ExpectedConditions.alertIsPresent());     
alert.authenticateUsing(new UserAndPassword(*username*, *password*));



回答2:


You can handle this in two ways:

  1. You can pass the username and password directly through the URL like this:

    driver..get("https://MyUserName:password@staging.www.abc.com")
    
  2. You can also use AutoIT Tool for handling any kind of window popups.

    • For this you first have to download and install AutoIt
    • Then download SciTE4AutoIt3

    You can do scripting in it, or you can use Au3Recorder. It is not available in new versions of SciTE, but you can download it from old versions separately. Unzip it and copy:

    autoit-v3.3.14.0.zip\install\Extras\Au3Record
    

    to

    [@Install Dir of AutoIt in Program files]\Extras\Au3Record
    

Now you can start the recorder directly by clicking Au3Record.exe or you can find it in the Script Editor window Tools >AU3Recorder.

For it you have to create a blank .au3 file in the Script Editor. Now start recording. Perform action on Window Popup. Stop when Done. Save it with .au3 format.

Now GO to Saved File location >> Right Click on the File and compile it (Compile Script(x64) or else). It will create an .exe file in the same folder.Now run that script in your Project using:

Runtime.getRuntime().exec("File Loaction/MyAutoItScript.exe");

It will work.




回答3:


I use Java for my test automation. I have searched for a decent way to deal with these sign in pop ups and cannot find one. The most common answers are either to include in a URL as prefix prior to the real url (eg https:\username:password@www.website.com) or to use a wait for alert. These have not worked for me as: on a form submit there is no simple url to use and I am not sure as to the security including the password in the start of the url; with the wait for alert the webdriver hangs until there is a response - which only comes from submitting the login response via the pop up.

The workaround I have found is poor - I've not got it to work in a headless environment and so limits this answers usefulness. Would be great to get a real answer here. Note that I am running this in a Windows environment and if I was using Linux I have read that I could use xvfb to provide a 'screen' for sikuli and then this would work - if anyone can comment on how to do this on a Windows server that would be MUCH appreciated.

I use Sikuli for the automation of things I cannot automate via Selenium. Sikuli does many things, including letting you basically feed it images that it performs actions on. For this purpose I run Sikuli on a thread started prior to clickin the submit that leads to the sign in pop-up. As it is running on a different thread it doesn't block the main thread, so it can still execute the log in. Once it logs in it shuts down and logging in closes the pop up and reactivates the main thread.

Specifically:

Sikuli MAVEN entry for POM:

<dependency>
    <groupId>com.sikulix</groupId>
    <artifactId>sikulixapi</artifactId>
    <version>1.1.4-20191010.160947-268</version>
</dependency>    

In the main code use a runnable executed via an executor:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
private final AtomicInteger expectedResultCount;
private final AtomicInteger publishedResultCount;    
private final ExecutorService executor; 
ExecutorService executor = Executors.newFixedThreadPool(5); 
String processName = "asic-login";
LoginPopUp login = new LoginPopUp(this, processName);
addResultExpectation(processName);
executor.execute(login);

The runnable here implements an interface I use to keep things tidy:

The main class implements the interface to manage the threads:

public class TestRunner implements ResultPublisher{ 

These are functions inside the main class for thread management:

private void addResultExpectation(String process){
    resultMap.put(process, new JSONObject());
    expectedResultCount.addAndGet(1);
}    

public void publishResult(JSONObject result){
    String process = result.getString("process-name");
    String strResult = result.getString("result");
    resultMap.put(process, result);
    publishedResultCount.addAndGet(1);
    if(publishedResultCount.get() == expectedResultCount.get()){
        executor.shutdown();       
        System.out.println("shutting down executor for run " + runId);
    }
}  

This is the interface

import org.json.JSONObject;
public interface ResultPublisher {
    void publishResult(JSONObject result);    
}

This is the runnable Runnable - an inner class in the TestRunner main class:

private class LoginPopUp implements Runnable{
        private ResultPublisher publisher;
        private String filePath;
        private String processName;
        private LoginPopUp(){            
        }

        public LoginPopUp(ResultPublisher publisher, String processName){
            this.publisher = publisher;
            this.processName = processName;
        }

        private void publish(JSONObject result){
            publisher.publishResult(result);
        }      

        public void run(){   
            JSONObject result = new JSONObject();
            result.put("path", filePath);
            try{
                Screen sd = new Screen();
                ScreenUtility s = new ScreenUtility(imagesDirectory);
                s.clickImage("LoginTitle.PNG", 10, 2500);
                s.typeImageWithOffset("UserName.PNG", userName, 30,0);
                s.typeImageWithOffset("Password.PNG",String.valueOf(password), 50,0);
                s.clickImage("AsicSignIn.PNG", 10, 250);
            }catch(Exception ex){
                result.put("result", ex.getMessage());
                result.put("process-name", processName);
                publish(result);
                Logger.getLogger(BCSRobot.class.getName()).log(Level.SEVERE, null, ex);
                return;                          
            }
            result.put("result", "logged in successfully");
            result.put("process-name", processName);
            publish(result);
            return;
        }
}    



回答4:


Try below code:

String username = "myUsername";
String password = "myPassword";
String URL = "http://" + username  + ":" + password + "@" + https://sso.mywebsite.com/usdf/ls/dia?kkkk;
driver.get(URL);  // Basically operation done here itself still if not work use further Alert code as well
Alert alert = driver.switchTo().alert();
alert.accept();  

Full code will be like:

driver.get("https://sso.mywebsite.com/usdf/ls/dia?kkkk");
String url = driver.getCurrentUrl().replaceAll("https://", "");
String username = "myUsername";
String password = "myPassword";
String URL = "https://" + username  + ":" + password + "@" + url;
driver.get(URL); // Basically operation done here itself still if not work use further Alert code as well
Alert alert = driver.switchTo().alert();
alert.accept();


来源:https://stackoverflow.com/questions/42358965/how-to-handle-authentication-alert-of-browser-in-selenium-webdriver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!