Playwright - 在 Java 中选择证书

问题描述 投票:0回答:1

我想使用 Playwright 打开一个网站,但当我尝试导航时,我收到以下信息:

该网站无法提供安全连接。 Mywebsite.com 不接受您的登录证书,或者可能尚未提供。尝试 联系系统管理员。 ERR_BAD_SSL_CLIENT_AUTH_CERT

Playwright 中存在一个普遍问题 - 它不支持开箱即用的客户端证书,多年来一直存在一个未解决的问题 (#1799)。有些人设法找到了解决方法,但使用的是 Javascript。我需要在 Java 中找到解决方法。路由选项不允许我修改请求中的复杂对象(例如证书),我尝试在浏览器上下文中使用 addInitScript 方法,但它不起作用。

const fs = require('fs');
const cert = fs.readFileSync('path/to/cert.cert');
const key = fs.readFileSync('path/to/key.key');
const passphrase = 'certPasswordValue';
const certOptions = { key, cert, passphrase };
const tls = require('tls');
const agent = new tls.Agent(certOptions);
window.fetch = (url, options) => {
  options.agent = agent;
  return window.origFetch(url, options);
};
javascript java certificate playwright client-certificates
1个回答
0
投票

阅读 github issues 我找到了解决方案

希望我的代码对你有帮助

import { BrowserContext } from "playwright";
import request from "request";

/**
 * Configura o contexto do navegador para rotear todas as solicitações por meio
 * de um agente com certificado PKCS12.
 * @param context O contexto do navegador onde as rotas serão configuradas.
 * @param pfxBuffer O buffer do arquivo de certificado PKCS12 (.pfx).
 * @param passphrase A senha para desbloquear o arquivo de certificado PKCS12.
 */

export default async function setupBrowserContext(
  context: BrowserContext,
  pfxBuffer: Buffer,
  passphrase: string
) {
  await context.route("**/*", (route, req) => {
    const options = {
      uri: req.url(),
      method: req.method(),
      headers: req.headers(),
      body: req.postDataBuffer(),
      timeout: 10000,
      followRedirect: false,
      agentOptions: {
        pfx: pfxBuffer,
        passphrase: passphrase,
      },
    };
    let firstTry = true;
    const handler = function handler(err: any, resp: any, data: any) {
      if (err) {
        if (firstTry) {
          firstTry = false;
          return request(options, handler);
        }
        console.error(`Unable to call ${options.uri}`, err.code, err);
        return route.abort();
      } else {
        return route.fulfill({
          status: resp.statusCode,
          headers: resp.headers,
          body: data,
        });
      }
    };
    return request(options, handler);
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.