Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Xử lý Authentication Popup (Basic Auth) với Selenium WebDriver Java

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 ChromeOptions với --disable-web-security (chỉ test environment).

Cách thay thế cho các loại Auth khác

Best Practice

  • Tạo test account riêng cho automation.
  • Dùng environment variable / secret manager cho credentials.
  • Trong CI/CD, cấu hình proxy authentication riêng thay vì nhúng vào URL test.
Loại AuthGiải pháp Selenium
Form-based LoginTìm element username/password/submit → sendKeys/click
Windows/NTLM/KerberosAutoIT, Robot class, hoặc cấu hình profile trình duyệt tự động đăng nhập
OAuth/SSOCookie injection, token injection, hoặc test API riêng biệt
Proxy AuthBrowserMob Proxy, hoặc extension Modify Headers