Basic authentication can be challenging when automating tests using Selenium. Unlike standard web forms, this requires handling browser pop-ups directly. In this article, we’ll explore three effective methods to handle Basic Authentication in Selenium C Sharp.
Possible Ways:
- Embedding Credentials(username and password) in the URL.
- Using AutoIT(Third Party Application) for Pop-up Handling.
- Using ChromeOptions(Set Properties) with HTTP Headers.
Embedding Credentials in the URL
The easiest way to handle basic authentication is to include the credentials in the URL:
var driver = new ChromeDriver(); string url = "http://username:password@example.com"; driver.Navigate().GoToUrl(url);
Note: This method may not work in all browsers due to security restrictions.
2. Using AutoIT for Pop-up Handling
AutoIT can simulate user interaction to handle browser pop-ups.
Install AutoIT from autoitscript.com.
Write a script to handle the pop-up:
WinWaitActive("[CLASS:#32770]") Send("yourUsername{TAB}") Send("yourPassword{ENTER}")
Call the script in your Selenium code:
System.Diagnostics.Process.Start("path/to/auth.exe"); driver.Navigate().GoToUrl("https://example.com");
3. Using ChromeOptions with HTTP Headers
Use ChromeOptions to pass authentication headers via a Chrome extension for a more advanced approach.
Download a Chrome extension like ModHeader.
Add the extension to your Selenium setup:
var options = new ChromeOptions(); options.AddExtension("path/to/auth-extension.crx"); var driver = new ChromeDriver(options); driver.Navigate().GoToUrl("https://example.com");
Best Practices:
Security: Never hard-code sensitive information in your scripts. Use environment variables or secure vaults.
Error Handling: Implement robust error handling to manage unexpected pop-ups.