You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用.pem文件的Karate API调用遇bad certificate错误求助

解决Karate中携带PEM证书请求API时的bad certificate错误

问题概述

在Insomnia中配置携带.pem证书的Token生成API请求可正常响应,但迁移到Karate后触发javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate错误。

Insomnia对应的curl命令:

curl --request POST \
  --url https://tokengenerator.com:8443/as/token.oauth2 \
  --header 'Cookie: PF=TmfprifldGj2sxCzWs3qYd; PF=TmfprifldGj2sxCzWs3qYd' \
  --header 'content-type: application/x-www-form-urlencoded' \
  --cookie PF=TmfprifldGj2sxCzWs3qYd \
  --data username=username \
  --data password=password \
  --data = \
  --data grant_type=password \
  --data client_id=TOKENCLIENT

当前Karate配置核心问题:

  • 错误将.pem证书配置为pkcs12格式,两者不兼容
  • SSL配置中的keyStoreHost值与请求域名不匹配
  • 未同步Insomnia中的Cookie配置

解决方案

1. 修正证书格式配置

方案一:直接使用PEM证书

Karate支持直接配置PEM格式客户端证书,无需转换格式:

var config = {
    env: env,
    CERT_FILE: 'src/test/resource/Client.pem'
};

karate.configure('ssl', {
    clientCert: config.CERT_FILE,
    clientCertPassword: 'password', // 证书有密码则填写,无则省略
    trustAll: true, // 测试环境临时用,生产建议配置信任库
    algorithm: 'TLS'
});

方案二:转换为PKCS12格式后使用

若必须用PKCS12,先通过OpenSSL将PEM转成P12文件:

openssl pkcs12 -export -in Client.pem -out Client.p12 -name "client-cert"

再修改Karate配置:

var config = {
    env: env,
    CERT_FILE: 'src/test/resource/Client.p12'
};

karate.configure('ssl', {
    keyStore: config.CERT_FILE,
    keyStorePassword: '你的P12文件密码',
    keyStoreType: 'pkcs12',
    trustAll: true,
    algorithm: 'TLS'
});

2. 同步请求Cookie配置

Insomnia请求中携带了PF Cookie,需在Karate Feature文件中补充:

Background:
    * configure ssl = true

Scenario: Token Generation - Success Response
    Given url 'https://tokengenerator.com:8443/as/token.oauth2'
    And header Content-Type = 'application/x-www-form-urlencoded'
    And cookie PF = 'TmfprifldGj2sxCzWs3qYd'
    And form field client_id = 'TOKENCLIENT'
    And form field grant_type = 'password'
    And form field username = 'username'
    And form field password = 'password'
    When method POST
    Then status 200

3. 验证基础配置正确性

  • 确认证书文件路径正确,可临时改用绝对路径测试
  • 检查证书文件有读取权限
  • 验证证书密码与Insomnia中配置完全一致

4. 开启SSL调试定位细节

若问题仍存在,开启Karate的SSL日志查看握手过程:

karate.configure('logSslTraffic', true);

内容的提问来源于stack exchange,提问作者Arun Mohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 17:57:17