Selenium WebDriver: Login to a website

Viewed 2584

Is there a way to login to a website without writing the actual password in the code. For example, I created a function to login:

var isAlreadyLogIn = false;

function LogIn (userId, password) {
    if (!isAlreadyLogIn) {
        driver.findElement(By.xpath("//*[@id='Email']")).sendKeys(userId);
        driver.findElement(By.xpath("//*[@id='Password']")).sendKeys(password);
        driver.findElement(By.xpath("//input[@value='Login']")).click();
        isAlreadyLogIn = true;
    }
}

it('Should login', function(done) {
    LogIn("username", "password");
});
3 Answers

Your code will need access to the credentials. I think the most common way to solve this is to put the credentials into a config file and read it from there. If you don't want the passwords to be included with the code you can just not commit in the config-file to the repository, but share it with a different means. Alternatively you could pass the username and password as command-line arguments to your tests.

Here are NodeJS examples how to store the credentials in different ways. The examples are for databases, but the idea is the same.

If you are using maven, an option is using the profiles and the override system properties.

    <profile>
        <id>QA</id>
        <properties>
            <runUrl>http://qaenvironment.com </runUrl>
            <admin.username>admin</admin.username>
            <admin.password>adminpass</admin.password>          
            <noadmin.username>noadmin</noadmin.username>
            <noadmin.password>qwerty123</noadmin.password>
        </properties>
    </profile>

Runing the execution whit the QA profile, for example, and in the Java code using that:

driver.findElement(By.xpath("//*[@id='Email']")).sendKeys(System.getProperty("admin.username"));
driver.findElement(By.xpath("//*[@id='Password']")).sendKeys(System.getProperty("admin.password"));
Related