如何在 Selenium 中处理基本身份验证而不在 URL 中嵌入凭证?

当前位置: 剧情吧 > Java>
电视猫时间: 2024-12-29 16:12:36

  如何在 Selenium 中处理基本身份验证而不在 URL 中嵌入凭证?

在 Selenium 中处理基本身份验证(Basic Authentication),而不直接在 URL 中嵌入凭证(如 http://username:password@website.com),可以通过以下方法实现:


1. 使用 WebDriver 的 Alert 接口

基本身份验证通常会触发浏览器的身份验证弹窗,可以使用 Selenium 的 Alert 接口来输入用户名和密码。

示例代码

import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class BasicAuthExample {
    public static void main(String[] args) {
        // 设置 ChromeDriver 路径
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        WebDriver driver = new ChromeDriver();

        // 打开需要基本身份验证的 URL
        driver.get("http://example.com/protected");

        // 切换到弹窗并输入凭证
        Alert alert = driver.switchTo().alert();
        alert.sendKeys("username" + "\t" + "password"); // 使用 Tab 分隔用户名和密码
        alert.accept(); // 确认登录

        // 后续操作
        System.out.println("Page Title: " + driver.getTitle());

        driver.quit();
    }
}

注意

  • 并非所有浏览器都支持通过 Alert 输入基本身份验证的凭证。
  • 此方法适用于简单的身份验证弹窗。

2. 使用自定义扩展插件(推荐,适合现代浏览器)

为 Chrome 或 Firefox 创建一个扩展程序,自动为请求添加 Authorization 头。

步骤

  1. 创建 Chrome 扩展程序

    • 创建一个包含 manifest.json 和 background.js 的文件夹。

    manifest.json 示例

    {
        "manifest_version": 3,
        "name": "Basic Auth Extension",
        "version": "1.0",
        "permissions": ["webRequest", "webRequestBlocking", "http://example.com/*"],
        "background": {
            "service_worker": "background.js"
        }
    }
    

    background.js 示例

    chrome.webRequest.onBeforeSendHeaders.addListener(
        function(details) {
            details.requestHeaders.push({
                name: "Authorization",
                value: "Basic " + btoa("username:password")
            });
            return { requestHeaders: details.requestHeaders };
        },
        { urls: ["http://example.com/*"] },
        ["blocking", "requestHeaders"]
    );
    
  2. 加载扩展到 Selenium

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    
    public class BasicAuthWithExtension {
        public static void main(String[] args) {
            System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
    
            ChromeOptions options = new ChromeOptions();
            options.addExtensions(new File("path/to/extension.crx"));
    
            WebDriver driver = new ChromeDriver(options);
            driver.get("http://example.com/protected");
    
            System.out.println("Page Title: " + driver.getTitle());
            driver.quit();
        }
    }
    

3. 使用 HTTP 客户端拦截请求(如 BrowserMob Proxy 或 Selenium Wire)

通过代理工具拦截 HTTP 请求并注入 Authorization 头。

示例代码(使用 Selenium Wire)

import com.github.tomakehurst.wiremock.client.BasicCredentials;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import io.github.bonigarcia.wdm.WebDriverManager;
import com.github.tomakehurst.wiremock.client.WireMock;

public class BasicAuthWithProxy {
    public static void main(String[] args) {
        WebDriverManager.chromedriver().setup();

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--proxy-server=http://localhost:8080");

        WebDriver driver = new ChromeDriver(options);

        // 配置代理,注入 Authorization 头
        WireMock.configureFor("localhost", 8080);
        WireMock.stubFor(
            WireMock.get(WireMock.urlPathMatching("http://example.com/protected"))
                .withBasicAuth("username", "password")
        );

        driver.get("http://example.com/protected");
        System.out.println("Page Title: " + driver.getTitle());

        driver.quit();
    }
}

注意

  • 需要依赖 Selenium Wire 或其他代理库。
  • 代理工具适合复杂场景(如动态注入头部)。

4. 使用浏览器启动参数

对于支持命令行参数的浏览器,可以在启动时传递身份验证信息。

示例代码

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class BasicAuthWithArgs {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        ChromeOptions options = new ChromeOptions();
        options.addArguments("user-data-dir=/path/to/user/profile"); // 使用带有已登录状态的浏览器配置
        options.addArguments("auth-server-whitelist=*example.com");

        WebDriver driver = new ChromeDriver(options);
        driver.get("http://example.com/protected");

        System.out.println("Page Title: " + driver.getTitle());
        driver.quit();
    }
}

最佳实践

  • 简单场景:使用 Alert 接口或 URL 嵌入凭证。
  • 复杂场景:推荐使用自定义扩展或代理工具(如 Selenium Wire)。
  • 安全性:避免在代码中硬编码用户名和密码,可以使用环境变量或安全存储工具。
    最新电视剧
    热门电视剧
    影视资讯
    最新剧情排行榜
    最新电视剧剧情