如何在@apollo/datasource-rest中使用客户端证书
新版@apollo/datasource-rest添加客户端证书的实现方法
1. 先创建带证书的https.Agent实例
首先生成配置了客户端证书的https.Agent,这一步和旧版逻辑一致:
const https = require('https'); const fs = require('fs'); // 初始化带客户端证书的https agent const clientHttpsAgent = new https.Agent({ cert: fs.readFileSync('/path/to/client-cert.pem'), // 客户端证书文件路径 key: fs.readFileSync('/path/to/client-key.pem'), // 客户端密钥文件路径 ca: fs.readFileSync('/path/to/ca-cert.pem'), // 可选:CA证书,用于验证服务端证书 keepAlive: true // 可选:开启连接复用,提升性能 });
2. 全局配置(所有请求自动携带证书)
如果你的所有请求都需要客户端证书,直接在RESTDataSource子类的构造函数中设置全局httpsAgent即可:
const { RESTDataSource } = require('@apollo/datasource-rest'); class MyCustomAPI extends RESTDataSource { constructor() { super(); this.baseURL = 'https://your-target-api.com/'; // 绑定全局https agent,所有HTTPS请求都会自动使用这个带证书的agent this.httpsAgent = clientHttpsAgent; } async getResourceData() { // 此请求会自动携带客户端证书 return this.get('/api/resource'); } }
3. 单个请求单独配置(仅指定请求携带证书)
如果只有部分请求需要证书,可在请求方法的第三个参数中传递agent选项:
async getSpecificData() { // 仅该请求使用带证书的agent return this.get('/api/specific-resource', null, { agent: clientHttpsAgent }); }
4. 通过钩子动态配置(灵活控制请求)
如果需要根据请求路径、参数等动态决定是否添加证书,可使用willSendRequest钩子:
class MyCustomAPI extends RESTDataSource { constructor() { super(); this.baseURL = 'https://your-target-api.com/'; this.clientAgent = clientHttpsAgent; } willSendRequest(request) { // 例如:仅对特定路径的请求添加证书 if (request.path.startsWith('/api/secure')) { request.context.fetchOptions = { ...request.context.fetchOptions, agent: this.clientAgent }; } } async getSecureData() { return this.get('/api/secure/data'); } async getPublicData() { // 此请求不会携带证书 return this.get('/api/public/data'); } }
内容的提问来源于stack exchange,提问作者J.R
相关产品推荐
相关产品推荐

