Khi truy cập trang web yêu cầu Basic Authentication, trình duyệt hiển thị popup đăng nhập (native dialog) mà Selenium không thể tương tác trực tiếp được (vì không phải web element).
Giải pháp: Nhúng credentials vào URL
Cú pháp: https://username:password@domain.com/path
String url = "https://admin:admin@the-internet.herokuapp.com/basic_auth"; driver.get(url);
Ví dụ hoàn chỉnh
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class BasicAuthExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
try {
String username = "admin";
String password = "admin";
String url = "https://" + username + ":" + password + "@the-internet.herokuapp.com/basic_auth";
driver.get(url);
// Verify đăng nhập thành công
String text = driver.findElement(By.cssSelector("p")).getText();
System.out.println("Nội dung sau auth: " + text);
// Expected: "Congratulations! You must have the proper credentials."
} finally {
driver.quit();
}
}
}
Lưu ý quan trọng
- Chỉ hoạt động với Basic Auth (HTTP Basic Authentication). Không dùng được cho form login, OAuth, SAML, Windows/NTLM auth.
- Ký tự đặc biệt: Nếu user/pass chứa ký tự đặc biệt (@, :, /, #...), phải URL-encode trước khi ghép vào URL:
String encodedUser = URLEncoder.encode(username, StandardCharsets.UTF_8); String encodedPass = URLEncoder.encode(password, StandardCharsets.UTF_8); String url = "https://" + encodedUser + ":" + encodedPass + "@example.com";
- Bảo mật: Credentials hiển thị rõ trong URL, lịch sử trình duyệt, log. Không dùng cho production credentials.
- Chrome 59+: Có thể bị chặn nếu URL quá dài hoặc policy bảo mật. Thử dùng
ChromeOptionsvới--disable-web-security(chỉ test environment).
Cách thay thế cho các loại Auth khác
| Loại Auth | Giải pháp Selenium |
|---|---|
| Form-based Login | Tìm element username/password/submit → sendKeys/click |
| Windows/NTLM/Kerberos | AutoIT, Robot class, hoặc cấu hình profile trình duyệt tự động đăng nhập |
| OAuth/SSO | Cookie injection, token injection, hoặc test API riêng biệt |
| Proxy Auth | BrowserMob Proxy, hoặc extension Modify Headers |