GCP Cloud Run上Remote Chrome WebDriver开启服务间认证后连接问题咨询
解决思路
Selenium Java SDK中,所有发往Remote WebDriver服务的HTTP请求均由HttpCommandExecutor类统一处理,身份认证头需要附加在每个HTTP请求上,因此仅需要扩展HttpCommandExecutor类即可,无需修改RemoteWebDriver的核心逻辑。
具体实现步骤
- 首先通过Google身份认证类生成针对你的Cloud Run服务的ID令牌
- 自定义继承
HttpCommandExecutor的实现类,重写请求执行方法,给所有发往Remote WebDriver的请求添加Authorization认证头 - 实例化
RemoteWebDriver时传入自定义的HttpCommandExecutor实例和Chrome配置即可
关键代码示例
首先实现带GCP认证的自定义Executor:
import com.google.auth.oauth2.IdTokenProvider; import com.google.auth.oauth2.IdTokenCredentials; import org.openqa.selenium.remote.HttpCommandExecutor; import org.openqa.selenium.remote.http.HttpRequest; import org.openqa.selenium.remote.http.HttpResponse; import java.io.IOException; import java.net.URL; public class GcpAuthHttpCommandExecutor extends HttpCommandExecutor { private final IdTokenCredentials idTokenCredentials; public GcpAuthHttpCommandExecutor(URL remoteAddress, IdTokenProvider idTokenProvider, String cloudRunAudience) throws IOException { super(remoteAddress); // 构造针对Cloud Run服务的ID令牌凭据 this.idTokenCredentials = IdTokenCredentials.newBuilder() .setIdTokenProvider(idTokenProvider) .setTargetAudience(cloudRunAudience) .build(); } @Override public HttpResponse execute(HttpRequest request) throws IOException { // 给每个请求添加GCP认证头 String idToken = idTokenCredentials.refreshAccessToken().getTokenValue(); request.addHeader("Authorization", "Bearer " + idToken); return super.execute(request); } }
然后实例化RemoteWebDriver时使用自定义Executor:
import com.google.auth.oauth2.GoogleCredentials; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.RemoteWebDriver; import java.net.URL; // 替换为你的Cloud Run服务根地址,同时作为ID令牌的受众参数 String cloudRunUrl = "https://<你的-cloud-run服务地址>"; // 获取GCP默认凭据,GCP环境下自动读取服务账号权限,本地调试可通过GOOGLE_APPLICATION_CREDENTIALS环境变量指定密钥文件 GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); if (!(credentials instanceof IdTokenProvider)) { throw new IllegalArgumentException("当前凭据不支持生成ID令牌"); } // 实例化自定义的带认证Executor GcpAuthHttpCommandExecutor executor = new GcpAuthHttpCommandExecutor(new URL(cloudRunUrl), (IdTokenProvider) credentials, cloudRunUrl); // 构造Chrome配置 ChromeOptions options = new ChromeOptions(); // 实例化RemoteWebDriver RemoteWebDriver driver = new RemoteWebDriver(executor, options);
注意事项
- 调用方服务使用的服务账号需要被授予
roles/run.invoker权限,才能调用开启了认证的Cloud Run服务 - ID令牌的受众(targetAudience)必须和Cloud Run服务的根URL完全一致,不能额外附加路径,否则认证会失败
- 本地调试时需要提前配置好Google应用凭据环境变量,确保凭据对应的账号拥有Cloud Run调用权限
内容的提问来源于stack exchange,提问作者YuriR
相关产品推荐
相关产品推荐

