Handle SSL Certificate Issue: How to Handle SSL Certificate Issue In Java Selenium Program?
You may have come across a situation where when you try to open some webpage manually, those are opening fine. Still, when trying to open the same site using Selenium WebDriver, you will get an error stating: “This Connection is Untrusted.”
When we try to open manually a URL on our system browser that time the browser already imported the required certificate that’s why we are not getting any error but when we try to open the same URL with selenium webdriver that time Selenium webdriver creates a fresh profile for each run and as the profile doesn’t have the SSL certificate so when you try to open using WebDriver you are getting this error screen.
What Is SSL Security Certificate?
SSL (Secure Sockets Layer) is a standard security protocol that is used to establish an encrypted connection between the server and client, which is a browser.
What is the untrusted certificate?
When you try to access a site that has the security certificate installed at that time, the certificate will help to determine whether the website you are visiting is the site that it claims to be. If there is any problem with the certificate, then that time, you will get an alert message or screen saying ‘This Connection Is Untrusted.’
Types of SSL Security Certificate Error
- Firefox: This connection is untrusted.
- Google Chrome: This site security is not trusted.
- Internet Explorer: This security certificate presented by this website was not trusted by a trusted certificate authority (CA).
How to Handle SSL Certificate Error In Firefox?
As we have mentioned that sometimes the firefox profile doesn’t have the certificate. That’s why we are getting the SSL: certificate error. SO to resolve this issue, we can create a Firefox profile manually, and after that, we can use the same profile with our selenium webdriver. So to resolve this follow the below steps:
- Create a firefox Profile
- Set the setAcceptUntrustedCertificates() method as true and setAssumeUntrustedCertificateIssuer() method to false
Selenium Automation Script For Firefox:
import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; public class SSLCertificate { public static void main(String[] args) { //It create firefox profile FirefoxProfile profile=new FirefoxProfile(); // This will set the true value profile.setAcceptUntrustedCertificates(true); // This will open firefox browser using above created profile WebDriver driver=new FirefoxDriver(profile); driver.get("pass the url as per your requirement"); } }
By following the above step, you can access the URL without any certificate issue.
How to Handle SSL Certificate Error In Chrome & IE?
Above we have seen how we can fix the certificate issues for the firefox browser, and now we are going to see how we can fix such issues in the chrome & IE browser also. In the Firefox browser, we have taken the help of a firefox profile, but for the chrome & IE browser, we need to take the help of Desired capabilities to get and accept the SSL certificate error on run time.
How To Test SSL Certificate?
We are going to discuss how we can handle the SSL Security Certificate error for different browsers like Chrome Browser, IE Browser, and Firefox Browser.
Steps for Chrome Browser:
- Create An object for Desiredcpabilities class
- Set the ACCEPT_SSL_CERTS as true
- Open the chrome browser with the capability
// Create object of DesiredCapabilities class DesiredCapabilities cap=DesiredCapabilities.chrome(); // Set ACCEPT_SSL_CERTS variable to true cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); // Set the driver path System.setProperty("webdriver.chrome.driver","Chrome driver path"); // Open browser with capability WebDriver driver=new ChromeDriver(cap);
Steps for IE Browser:
Like the Chrome browser, we need to follow the same process to handle the certificate issue for the IE browser.
// Create object of DesiredCapabilities class DesiredCapabilities cap=DesiredCapabilities.internetExplorer(); // Set ACCEPT_SSL_CERTS variable to true cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); // Set the driver path System.setProperty("webdriver.ie.driver","IE driver path"); // Open browser with capability WebDriver driver=newInternetExplorerDriver(cap);
package com.selenium.basics; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; public class SSLCertificateIssue { public static void main(String[] args) { DesiredCapabilities cap=new DesiredCapabilities(); cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); WebDriver driver=new FirefoxDriver(); driver.get("http://www.cacert.org/"); driver.close(); } }
Read Also: Handle Tooltip Java Selenium
This article covers what is an SSL certificate is and how to fix SSL certificate error in selenium.
Selenium makes repetitive test tasks easier by simulating human interactions in the web browser, but there are specific differences in how tests are run through automation.
We may have encountered a case where manually opening a website works fine, but the same action via Selenium WebDriver will result in an error message stating that this connection is not trusted.
Have you ever wondered why this is happening? The answer is simple: if you manually open a URL, the browser will automatically import the required certificates and no error will occur. At the same time, every execution in Selenium WebDriver takes place in a new profile that does not have the SSL(Secure Sockets Layer) certificates, hence the error keeps occurring.
In this article, You will learn everything about SSL certificate and learn how we can deal with SSL certificate in Selenium and take appropriate measures in the event of SSL certificate errors in different browsers.
SSL (Secure Sockets Layer) is a standard security protocol that creates a secure connection between the server and the client (browser). Information sent with an SSL certificate is encrypted and ensures that it is sent to the correct server. It is a website identity validator and helps get rid of hackers.
Steps to Fix SSL certificate error
We can handle the SSL error by using the below code
- Create ChromeOptions Instance
ChromeOptions SSLhandling = new ChromeOptions();
- Use the accept insecure certs method with true as a value to accept the untrusted certificate
SSLhandling.setAcceptInsecureCerts(true);
- Creating an instance of Chrome driver by passing reference of ChromeOptions object
WebDriver driver = new ChromeDriver(SSLhandling);
- Launch the application
driver.get("https://www.swingli.com/");
System.out.println("The page title is : " +driver.getTitle());
driver.quit();
Conclusion
This article covered what is SSL and how to fix SSL certificate error in selenium chrome drivers. We hope it resolved your problem of such an issue. Happy Automating
What is an SSL Certificate?
SSL (Secure Sockets Layer) is a security protocol to establish a secure connection between the server and the client called the browser. An SSL certificate creates security through which usernames, passwords, credit card numbers information can pass safely. SSL Certificates validate the identity of the websites and encrypt the visitors send to, or receive from information from your site. This keeps hackers from spying on any exchange of information between you and your visitors.
What is an untrusted certificate?
When users try to open a site that has the security certificate installed, then the certificate will help the user to determine whether the website you are opened is the site that it claims to be. The user will get an alert message if there is any problem with the certificate saying ‘This Connection is Untrusted’.
Benefits of SSL Certificate
- One can easily increase their users’ and customers’ trust by enhancing business growth rapidly.
- An SSL certificate creates a secure online transactions and customers information like usernames, passwords, credit card numbers, debit card information.
- Keep hackers from spying the information.
- Boosts in ranking and increase brand value. In Google website gets better ranking if it is SSL Certificates is valid.
- Secure payments to experience safe shopping.
SSL-Certificate websites start with https:// where you can see a lock icon or green address bar if the connection is secure.
For example, through net banking, if you want to do some transaction or want to purchase any item through e-commerce sites such as Myntra or Amazon.
What happens between the Web Browser and the Server?
- The browser will request the webserver to identify by itself and it tries to connect with a website secured with SSL.
- To the browser, the server will send a copy of its SSL certificate.
- The browser will verify whether the SSL certificates is valid. If yes, it will send a message to the server
- To start an SSL encrypted session the server will send back a digitally signed acknowledgment and between the server and the browser, the encrypted data is shared.
In doing so, you need to send out sensitive information such as credit or debit card details or login credentials and that has to send out securely so that it cannot be hacked by hackers.
For Example
- Type https://www.amazon.com/
- Click Enter.
- You will see an address bar in the browser as below:-
Types of SSL Certificates
Using the SSL Certificate mechanism the browser and server can establish a secure connection. This connection havs three types of certificates.
- Root
- Intermediate
- Server Certificate
Process of getting an SSL Certificate
The process of getting an SSL certificate follow below steps:-
- First, you need to create a CSR (Certificate Signing Request) request.
- CSR request will create a CSR data file, which is sent to the SSL certificate issue i.e CA (Certificate Authority).
- The Certificate Authority will use the CSR data files to create an SSL certificate for your server.
- You have to install it on your server once after receiving the SSL certificate.
- You also need to install an intermediate certificate which ties your SSL certificate with CA’s root certificate.
Types of SSL Certificate Errors
Suppose in the web-browser you type some website URL request and get a message as “This connection is Untrusted” or the “The site’s security certificate is not trusted” based on the browser you are using. Then such error leads to an SSL certificate error.
Now, with the requested certificate if the browser is unable to establish a connection, then the browser will throw an “Untrusted Connection” exception.
The certificate errors you see in different browsers are
- Firefox – This connection is untrusted
- Google Chrome -This site security is not trusted
- Internet Explorer ( IE) – This security certificate presented by this website was not trusted by a trusted certificate authority (CA)
How to Handle SSL Certificate Error in Firefox browser?
In the Firefox browser sometimes we get the SSL certificate error because the firefox profile doesn’t have the certificate, so to overcome this issue, we manually create a Firefox profile, and we use the same profile with our selenium webdriver. We follow the below steps to resolve this:
- Create a firefox Profile
- Now we need to set the setAcceptUntrustedCertificates() method to true and in the Firefox profile set the method setAssumeUntrustedCertificateIssuer() to false
Selenium Automation Script for Firefox:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class SSLCertificateHandleFirefox
{
public static void main(String[] args)
{
//Creation of firefox profile
FirefoxProfile profile=new FirefoxProfile();
// It set the value to true
profile.setAcceptUntrustedCertificates(true);
// It will open the firefox browser through above created profile
WebDriver driver=new FirefoxDriver(profile);
driver.get("pass the URL of the browser");
}
}
Handling of SSL Certificate Error in Chrome & IE browser?
With the help of a firefox profile in the Firefox browser, we handle SSL certificate errors, but for the chrome & IE browser, to get and accept the SSL certificate error on run time we take the help of desired capabilities.
How to Test an SSL Certificate?
We are going to learn how we can handle the SSL Security Certificate error for different browsers like Chrome Browser, IE Browser, and Firefox Browser.
Steps for Chrome Browser:
- For Desiredcpabilities class create the object
- Set the ACCEPT_SSL_CERTS as true
- With the capability open the chrome browser
// Create the object of DesiredCapabilities class using chrome
DesiredCapabilities capability=DesiredCapabilities.chrome();
// Set ACCEPT_SSL_CERTS variable to true
capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
// Set the chrome driver path
System.setProperty("webdriver.chrome.driver","Path of the Chrome driver");
System.setProperty("webdriver.chrome.driver", "C:\Users\chromedriver_win32\chromedriver.exe");
// Open the browser
WebDriver driver=new ChromeDriver(capability);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Enter the site URL where you are facing SSL error.
driver.get("Enter site URL");
Steps for IE Browser:
We follow the same process as we follow for the Chrome browser in the IE browser to handle the certificate issue.
// Create object of DesiredCapabilities class for IE browser
DesiredCapabilities capabilities=DesiredCapabilities.internetExplorer();
// Set ACCEPT_SSL_CERTS variable to true
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
// Set the driver path
System.setProperty("webdriver.ie.driver","Path of the IE driver ");
System.setProperty("webdriver.chrome.driver", "C:\Usersiedriver_win32\internetexplorerdriver.exe");
// Open browser with capability
WebDriver driver=newInternetExplorerDriver(capabilities);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Enter the site URL where you are facing SSL error.
driver.get("Enter site URL");
What is an SSL Certificate?
SSL (Secure Sockets Layer) is a security protocol to establish a secure connection between the server and the client called the browser. An SSL certificate creates security through which usernames, passwords, credit card numbers information can pass safely. SSL Certificates validate the identity of the websites and encrypt the visitors send to, or receive from information from your site. This keeps hackers from spying on any exchange of information between you and your visitors.
What is an untrusted certificate?
When users try to open a site that has the security certificate installed, then the certificate will help the user to determine whether the website you are opened is the site that it claims to be. The user will get an alert message if there is any problem with the certificate saying ‘This Connection is Untrusted’.
Benefits of SSL Certificate
- One can easily increase their users’ and customers’ trust by enhancing business growth rapidly.
- An SSL certificate creates a secure online transactions and customers information like usernames, passwords, credit card numbers, debit card information.
- Keep hackers from spying the information.
- Boosts in ranking and increase brand value. In Google website gets better ranking if it is SSL Certificates is valid.
- Secure payments to experience safe shopping.
SSL-Certificate websites start with https:// where you can see a lock icon or green address bar if the connection is secure.
For example, through net banking, if you want to do some transaction or want to purchase any item through e-commerce sites such as Myntra or Amazon.
What happens between the Web Browser and the Server?
- The browser will request the webserver to identify by itself and it tries to connect with a website secured with SSL.
- To the browser, the server will send a copy of its SSL certificate.
- The browser will verify whether the SSL certificates is valid. If yes, it will send a message to the server
- To start an SSL encrypted session the server will send back a digitally signed acknowledgment and between the server and the browser, the encrypted data is shared.
In doing so, you need to send out sensitive information such as credit or debit card details or login credentials and that has to send out securely so that it cannot be hacked by hackers.
For Example
- Type https://www.amazon.com/
- Click Enter.
- You will see an address bar in the browser as below:-
Using the SSL Certificate mechanism the browser and server can establish a secure connection. This connection havs three types of certificates.
- Root
- Intermediate
- Server Certificate
Process of getting an SSL Certificate
The process of getting an SSL certificate follow below steps:-
- First, you need to create a CSR (Certificate Signing Request) request.
- CSR request will create a CSR data file, which is sent to the SSL certificate issue i.e CA (Certificate Authority).
- The Certificate Authority will use the CSR data files to create an SSL certificate for your server.
- You have to install it on your server once after receiving the SSL certificate.
- You also need to install an intermediate certificate which ties your SSL certificate with CA’s root certificate.
Types of SSL Certificate Errors
Suppose in the web-browser you type some website URL request and get a message as “This connection is Untrusted” or the “The site’s security certificate is not trusted” based on the browser you are using. Then such error leads to an SSL certificate error.
Now, with the requested certificate if the browser is unable to establish a connection, then the browser will throw an “Untrusted Connection” exception.
The certificate errors you see in different browsers are
- Firefox – This connection is untrusted
- Google Chrome -This site security is not trusted
- Internet Explorer ( IE) – This security certificate presented by this website was not trusted by a trusted certificate authority (CA)
How to Handle SSL Certificate Error in Firefox browser?
In the Firefox browser sometimes we get the SSL certificate error because the firefox profile doesn’t have the certificate, so to overcome this issue, we manually create a Firefox profile, and we use the same profile with our selenium webdriver. We follow the below steps to resolve this:
- Create a firefox Profile
- Now we need to set the setAcceptUntrustedCertificates() method to true and in the Firefox profile set the method setAssumeUntrustedCertificateIssuer() to false
Selenium Automation Script for Firefox:
import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; public class SSLCertificateHandleFirefox { public static void main(String[] args) { //Creation of firefox profile FirefoxProfile profile=new FirefoxProfile(); // It set the value to true profile.setAcceptUntrustedCertificates(true); // It will open the firefox browser through above created profile WebDriver driver=new FirefoxDriver(profile); driver.get("pass the URL of the browser"); } }
Handling of SSL Certificate Error in Chrome & IE browser?
With the help of a firefox profile in the Firefox browser, we handle SSL certificate errors, but for the chrome & IE browser, to get and accept the SSL certificate error on run time we take the help of desired capabilities.
How to Test an SSL Certificate?
We are going to learn how we can handle the SSL Security Certificate error for different browsers like Chrome Browser, IE Browser, and Firefox Browser.
Steps for Chrome Browser:
- For Desiredcpabilities class create the object
- Set the ACCEPT_SSL_CERTS as true
- With the capability open the chrome browser
// Create the object of DesiredCapabilities class using chrome DesiredCapabilities capability=DesiredCapabilities.chrome(); // Set ACCEPT_SSL_CERTS variable to true capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); // Set the chrome driver path System.setProperty("webdriver.chrome.driver","Path of the Chrome driver"); System.setProperty("webdriver.chrome.driver", "C:\Users\chromedriver_win32\chromedriver.exe"); // Open the browser WebDriver driver=new ChromeDriver(capability); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //Enter the site URL where you are facing SSL error. driver.get("Enter site URL");
Steps for IE Browser:
We follow the same process as we follow for the Chrome browser in the IE browser to handle the certificate issue.
// Create object of DesiredCapabilities class for IE browser DesiredCapabilities capabilities=DesiredCapabilities.internetExplorer(); // Set ACCEPT_SSL_CERTS variable to true capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); // Set the driver path System.setProperty("webdriver.ie.driver","Path of the IE driver "); System.setProperty("webdriver.chrome.driver", "C:\Usersiedriver_win32\internetexplorerdriver.exe"); // Open browser with capability WebDriver driver=newInternetExplorerDriver(capabilities); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //Enter the site URL where you are facing SSL error. driver.get("Enter site URL");
Conclusion:
- SSL (Secure Sockets Layer) is a standard security protocol will establish a secure connection between the client and the server
- To establish a secure connection the browser and the server use the SSL Certificate mechanism.
- SSL certificate error will occur when a secure connection is not established between the client and the server.
Что такое SSL-сертификат?
SSL (Secure Sockets Layer) — это стандартный протокол безопасности для установления безопасного соединения между сервером и клиентом, который является браузером.
Сертификат SSL (Secure Socket Layer) обеспечивает безопасное преобразование данных через сервер и клиентское приложение, используя строгий стандарт шифрования или цифровую подпись. Нужно установить сертификат SSL или сертификат подписи кода.
В этом уроке вы узнаете
- Что такое SSL-сертификат?
- Преимущества SSL-сертификата
- Как сертификат SSL создает безопасное соединение
- Типы SSL-сертификатов
- Как проверяются сертификаты SSL
- Типы ошибок SSL-сертификатов
- Как обработать ошибку сертификата SSL с помощью Selenium Webdriver
- Обработка ошибок сертификата SSL в Firefox
- Обработка ошибок сертификата SSL в Chrome
- Обработка ошибок сертификата SSL в IE
Преимущества SSL-сертификата
Есть ряд преимуществ использования SSL-сертификата, таких как,
- Можно повысить доверие своих пользователей и клиентов, чтобы быстро увеличить рост бизнеса.
- Эти сертификаты помогают защитить онлайн-транзакции и конфиденциальную информацию клиентов, такую как данные кредитной или дебетовой карты и т. Д.
- Подписание сертификата имеет тенденцию получать максимальное количество скачиваний и хорошие отзывы от пользователей.
Веб-сайты, защищенные SSL, начинаются с https: //, и вы можете видеть значок замка или зеленую адресную строку, если соединение установлено безопасно.
Например, если вы хотите совершить какую-либо транзакцию через интернет-банкинг или купить мобильный телефон через сайт электронной коммерции, например, Flipkart или Amazon.
Что происходит между веб-браузером и сервером
- Браузер пытается подключиться к веб-сайту, защищенному с помощью SSL. Браузер просит веб-сервер идентифицировать себя
- Сервер отправляет браузеру копию своего SSL-сертификата.
- Браузер проверяет подлинность SSL-сертификата. Если это так, он отправляет сообщение на сервер
- Сервер отправляет обратно подтверждение с цифровой подписью, чтобы начать сеанс с шифрованием SSL
- Зашифрованные данные передаются между сервером и браузером
При этом вам необходимо передавать конфиденциальную информацию, такую как номера кредитных карт или учетные данные для входа в систему, которая должна быть защищенной, чтобы ее нельзя было взломать или перехватить.
Например
- Введите https://netbanking.hdfcbank.com/netbanking/ .
- Нажмите Enter.
- Вы увидите зеленую адресную строку в браузере, как показано ниже: —
Как сертификат SSL создает безопасное соединение
- Браузер отправляет HTTPS-запрос на сервер.
- Теперь сервер должен предоставить некоторую идентификацию браузеру, чтобы доказать, что он является доверенным. Это можно сделать, отправив копию своего SSL-сертификата в браузер.
- Каждый браузер имеет свой собственный список доверенных ЦС. Браузер проверяет корневой каталог сертификата на соответствие списку доверенных центров сертификации, а также на то, что срок действия сертификата не истек, он не был отменен и что общее имя действительно для веб-сайта, к которому он подключается.
- Если браузер доверяет сертификату, между сервером и браузером создается зашифрованный сеанс.
- Сервер и браузер могут отправлять зашифрованные сообщения
Типы SSL-сертификатов
Браузер и сервер используют механизм SSL-сертификатов, чтобы установить безопасное соединение. Это соединение включает проверку трех типов сертификатов.
- корень
- промежуточный
- Сертификат сервера
Процесс получения SSL-сертификата
Процесс получения SSL-сертификата включает в себя следующие шаги:
- Сначала необходимо создать запрос CSR (создать запрос на подпись сертификата).
- Запрос CSR создает файл данных CSR, который отправляется эмитенту сертификата SSL, известному как CA (центр сертификации).
- CA использует файлы данных CSR для создания SSL-сертификата для вашего сервера.
- Получив сертификат SSL, вы должны установить его на свой сервер.
- Также необходимо установить промежуточный сертификат, который связывает ваш SSL-сертификат с корневым сертификатом CA.
На изображении ниже представлены все три сертификата — корневой, промежуточный и серверный.
Как проверяются сертификаты SSL
SSL работает через комбинацию программ и процедуры шифрования / дешифрования, которые существуют на компьютере веб-сервера и в браузере веб-сервера.
SSL-сертификат в основном содержит нижеприведенную информацию.
- Тема, которая является личностью владельца сайта.
- Достоверность информации — открытый и закрытый ключи.
Закрытый и открытый ключи — это два уникально связанных криптографических ключа (числа). Все, что зашифровано открытым ключом, может быть расшифровано только закрытым ключом.
Если из-за сертификата не установлено безопасное соединение между сервером и клиентом, появится следующая ошибка сертификата SSL.
Типы ошибок SSL-сертификатов
Предположим, вы набрали в браузере какой-то запрос https и получили сообщение, например «Это соединение ненадежное» или «Сертификат безопасности сайта не является доверенным», в зависимости от используемого вами браузера. Тогда такая ошибка является предметом ошибки сертификата SSL.
Теперь, если браузер не может установить защищенное соединение с запрошенным сертификатом, он выдаст исключение «Ненадежное соединение», как показано ниже, и попросит пользователя предпринять соответствующие действия.
Типы ошибок, которые вы можете увидеть из-за сертификата в разных браузерах, могут быть примерно такими
- FireFox — это соединение не заслуживает доверия
- Google Chrome — безопасности этого сайта не доверяют
- Internet Explorer (IE) — этот сертификат безопасности, представленный данным веб-сайтом, не является доверенным доверенным центром сертификации (CA)
Как обработать ошибку сертификата SSL с помощью Selenium Webdriver
Предположим, что мы написали несколько тестовых сценариев и, выполняя сценарий, мы обнаружили в ситуации «Ненадежное соединение» выше, как мы обрабатываем исключение исключительно посредством автоматизации.
В таком случае мы должны настроить наш скрипт таким образом, чтобы он сам позаботился об исключении SSL.
Сценарии должны быть изменены в соответствии с типом экземпляра браузера, который мы используем. Это когда желаемые возможности появляются на картинке.
Требуемые возможности используются для настройки экземпляра драйвера Selenium Webdriver. С помощью желаемых возможностей можно настроить все экземпляры драйверов, такие как ChromeDriver, FirefoxDriver и Internet Explorer.
На данный момент у нас нет конкретного URL для создания вышеуказанного сценария, но я предоставляю шаги, которые мы можем добавить в сценарий Selenium для обработки описанной выше ситуации «Ненадежное соединение».
Обработка ошибок сертификата SSL в Firefox
Для обработки ошибки сертификата SSL в Firefox нам нужно использовать требуемые возможности Selenium Webdriver и выполнить следующие шаги.
Шаг 1) : Сначала нам нужно создать новый профиль Firefox с именем « myProfile ». Вы можете обратиться к Google, чтобы узнать «Как создать» профиль Firefox. Это просто и легко.
Шаг 2) : Теперь откройте myProfile в скрипте, как показано ниже, и создайте объект FirefoxProfile.
ProfilesIni prof = new ProfilesIni() FirefoxProfile ffProfile= prof.getProfile ("myProfile")
Шаг 3) : Теперь нам нужно установить свойства « setAcceptUntrustedCertificates » и « setAssumeUntrustedCertificateIssuer » в профиле Fire Fox.
ffProfile.setAcceptUntrustedCertificates(true) ffProfile.setAssumeUntrustedCertificateIssuer(false)
Шаг 4) : теперь используйте профиль FireFox в объекте драйвера FireFox.
WebDriver driver = new FirefoxDriver (ffProfile)
Примечание . «SetAcceptUntrustedCertificates» и «setAssumeUntrustedCertificateIssuer » являются возможностями для обработки ошибок сертификата в веб-браузерах.
Обработка ошибок сертификата SSL в Chrome
Для обработки ошибки SSL в Chrome нам нужно использовать нужные возможности Selenium Webdriver. Приведенный ниже код поможет принять все SSL-сертификаты в Chrome, и пользователь не получит никаких ошибок, связанных с SSL-сертификатами, используя этот код.
Нам нужно создать экземпляр класса DesiredCapabilities, как показано ниже:
DesiredCapabilities handlSSLErr = DesiredCapabilities.chrome () handlSSLErr.setCapability (CapabilityType.ACCEPT_SSL_CERTS, true) WebDriver driver = new ChromeDriver (handlSSLErr);
Обработка ошибок сертификата SSL в IE
В отличие от обработки SSL-сертификатов в браузере Chrome и Firefox, в IE вам, возможно, придется обрабатывать его с помощью JavaScript.
Для обработки SSL-сертификата в IE вы можете справиться с этой ситуацией двумя способами:
- При этом вы перейдете по ссылке « Перейти на этот сайт (не рекомендуется)». Далее мы увидим, как обрабатывать ошибки SSL в IE.
Заметив ошибку сертификата SSL в браузере IE, вы найдете ссылку «Перейти на этот сайт (не рекомендуется)». Эта ссылка имеет идентификатор «переопределить ссылку». Вы можете просмотреть идентификатор в режиме HTML с помощью F12.
Нажмите на ссылку, используя метод driver.navigate () с JavaScript, как показано ниже: —
driver.navigate ().to ("javascript:document.getElementById('overridelink').click()");
- Второй метод очень похож на Chrome SSL Handling code
DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); System.setProperty("webdriver.ie.driver","IEDriverServer.exe"); WebDriver driver = new InternetExplorerDriver(capabilities);
Приведенный выше код поможет обработать ошибку сертификата SSL в IE.
Резюме:
- SSL (Secure Sockets Layer) — это стандартный протокол безопасности для установления безопасного соединения между сервером и клиентом.
- Браузер и сервер используют механизм SSL-сертификатов, чтобы установить безопасное соединение.
- SSL работает через комбинацию программ и процедуры шифрования / дешифрования, которые существуют на компьютере веб-сервера и в браузере веб-сервера.
- Если между сервером и клиентом не установлено безопасное соединение из-за сертификата, возникнет ошибка сертификата SSL
- Нужно настроить наш скрипт таким образом, чтобы он самостоятельно позаботился об исключении / ошибке SSL через веб-драйвер Selenium.
In the previous tutorial discussed the technique to find all the broken links of any website. Today we will talk about the website’s trust and security which is determined by the Certificate Authority. In short, we call the CA enabled. Our agenda for this tutorial is about handling SSL untrusted certificate error message through Selenium. We also call it handling SSL certificate message through Selenium.
Why do we get SSL Untrusted certificate error message?
We get SSL untrusted certificate error message when webmaster changes the URL protocol from http:// to https:// and he forgot to configure the CA certificate on its server. When any browser fetches URL with https prefix then it tries to find out SSL certificate installed file on its server. If it does not get any CA certificate or the certificate is self-signed (not signed by any authority body) then it throws SSL untrusted certificate error message.
Hope it clears your confusion. 😊
Free Advice: Either you fully implement https or keep http only.
What is a Secure Socket Layer certificate?
In short, we call Secure Socket Layer as SSL. It is the secured HTTP protocol (HTTPS) which establishes a secured connection between the server and the client (browser). Installation of SSL certificate ensures the secure and safe browsing of the web page and it is responsible for secured data exchange in encrypted form.
Significances of having an SSL certificate
There are various significances of having an SSL certificate on the site. It gives the advantage to the website in many ways, some are listed as follows:
- It helps to develop the feeling of trust among the users
- SSL is the secured way to integrate payment facility on the website. That is why all the e-commerce portals and banking portals have HTTPS. You can validate it by yourself.
- It attracts more user due to security
- A website is also secured from the attackers as it restricts Cross Site Scripting and other breaches
- It helps to establish any business as the authority
- Overall security observed for users as well as owner
How to get an SSL certificate for the website?
These days web host provider already installs the CA certificate, you only need to enable it on your website. You can reach your hosting provider for the confirmation.
If you do not have pre-installed CA certificate on your server, then you need a CA certificate from the authority. It is paid as well as free. Let’s Encrypt is an online portal which offers free, automated and opened CA certification. Get it and ask your hosting provider to install on your server.
How to handle SSL untrusted certificate error message using Selenium WebDriver?
You got the basic concepts of SSL untrusted certificate. We get different SSL untrusted certificate error message in the different browser. Below image is the compilation of different SSL untrusted certificate error message taken for the different browser.
Let’s have a look into the sample codes to handle SSL untrusted certificate error message in Selenium WebDriver.
Handling SSL untrusted certificate error in Chrome
System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe"); ChromeOptions option = new ChromeOptions(); option.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); WebDriver driver = new ChromeDriver(option);
Handling SSL untrusted certificate error in Firefox
System.setProperty("webdriver.gecko.driver", "path of geckodriver.exe"); FirefoxOptions foxOpt = new FirefoxOptions(); foxOpt.setAcceptInsecureCerts(true); WebDriver driver = new FirefoxDriver(foxOpt);
Handling SSL untrusted certificate error in Internet Explorer
System.setProperty("webdriver.ie.driver", "path of iedriver.exe"); InternetExplorerOptions ieOpt = new InternetExplorerOptions(); ieOpt.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); WebDriver driver = new InternetExplorerDriver(ieOpt);
These are sample code for Chrome, Firefox and Internet Explorer. So, when we need to handle the untrusted certificate error message then we need to call the profile options of the browser. In the above code you see the implementation is similar, but with different calls.
This was all about handling SSL untrusted certificate error message using Selenium WebDriver. You can ask your queries using below comment form and don’t miss to join our Facebook community for more updates on Test automation.
About The Author
Avinash Mishra
Avinash Mishra is the author of Inviul blog. He is a software engineer and blogger by choice. He loves to write blogs, and apart from blogging, he is interested in documentary film making, listening to music, traveling around the world and philanthropic activities.