首页 > 解决方案 > 在 NestJS 中向 HTTP 请求添加证书

问题描述

我正在研究 NestJS API,并且想了解传出请求和证书。我们需要从 API 中发出请求以允许其运行,但此 API 需要特定的证书。我的计算机上有证书,但不知道如何通过它们作为选项。如果可能的话,我也想避免使用新的 NPM 包,但这不是必需的。

这也是在创建应用程序之前在main.ts文件中完成的,因此以下内容将无法正常工作:

const app = await NestFactory.create(ApplicationModule, {
    httpOptions: {
      ca: readFileSync('path/to/cert/file')
    }
  });

我将以下内容视为其他语言的“解决方案”:

ca: readFileSync('path/to/certificate')

HttpService但是,这在NestJS的任何地方都不被接受。

这是我的意思的一个例子:

示例.service.ts

import { HttpService, Injectable } from '@nestjs/common';
import * as fs from 'fs';

@Injectable()
export class ExampleService {
  constructor(private http: HttpService) { }

  async getRequest() {
    let response = null;

    const options = {
      headers: {
        'Content-Type': 'application/json'
      },
      ca: readFileSync('certs/cert.pem')
    };

    await this.http.get('http://apiurl.com/endpoint/path', options).subscribe(res => {
      response = res;
    };

    return response;
  }
}

目前 HttpService 的问题是它需要一个“配置”作为第二个参数,这个参数是一个 AxiosRequestConfig。这没有任何参数ca,因此它无法识别上述代码,并且无法找到文档使得弄清楚这一点变得更加困难。

我还尝试使用 NodeJS 使用和调用的默认 http/https 包http.request(),但即使是那里的文档也没有任何关于证书的内容。

我已经考虑过拦截请求的可能性,但找不到更多信息以及我们如何将证书添加到选项中。

我也使用过export NODE_EXTRA_CA_CERTS=./certs/certificate.pem,但正在寻找一种更具体的解决方案,允许特定请求获得某些认证,而其他请求则没有。

有没有办法在不安装另一个 npm 包的情况下解决这个问题?

如果重复没有帮助,请回答!

由于 HttpService 建立在 http/https 之上,它利用 Axios 来处理所有请求。为了向特定请求添加证书,您需要创建一个代理,这是从 https 导入的。

1:创建代理如:

const httpsAgent = https.Agent({ca: fs.readFileSync('path/to/cert/file'});

2.)将 httpsAgent 添加到请求选项中,对象中有一个属性:

const reqOptions = {
httpsAgent: this.httpsAgent
};

3.) 将其添加到 AxiosRequestConfig 中的请求中,它是任何请求中的最后一个参数:

this.http.get('http://apiurl.com/endpoint', reqOptions);

这就对了!成品看起来像这样:

示例.service.ts

import { HttpService, Injectable } from '@nestjs/common';
import * as fs from 'fs';

@Injectable()
export class ExampleService {
  httpsAgent = null;

  constructor(private http: HttpService) {
    this.httpsAgent = new https.Agent({ca: fs.readFileSync('path/to/cert/file')});
  }

  async getRequest() {
    let response = null;

    const options = {
      headers: {
        'Content-Type': 'application/json'
      },
      httpsAgent: this.httpsAgent;
    };

    await this.http.get('http://apiurl.com/endpoint/path', options).subscribe(res => {
      response = res;
    };

    return response;
  }
}

标签: node.jshttpaxioscertificatenestjs

解决方案


推荐阅读