我目前正在NestJS项目中使用Swagger,并且启用了浏览器:

main.js年后

const options = new DocumentBuilder()
    .setTitle('My App')
    .setSchemes('https')
    .setDescription('My App API documentation')
    .setVersion('1.0')
    .build()

const document = SwaggerModule.createDocument(app, options)
SwaggerModule.setup('docs', app, document, {
    customSiteTitle: 'My App documentation',
})

有了这个,探险者可以在/docs分钟内进入,这是我所期望的.但是我想知道是否可以在浏览器中添加任何身份验证层,这样只接受某些请求.

我想让这个资源管理器在生产环境中可以访问,但仅限于经过身份验证的用户.

提前感谢:)

推荐答案

Securing access to your Swagger with HTTP Basic Auth using NestJS with Express

首先运行npm i express-basic-auth,然后将以下内容添加到main.{ts,js}:

// add import
import * as basicAuth from 'express-basic-auth';

// ...

// Sometime after NestFactory add this to add HTTP Basic Auth
app.use(
    ['/docs', '/docs-json'],
    basicAuth({
        challenge: true,
        users: {
            yourUserName: 'p4ssw0rd',
        },
    }),
);


// Your code
const options = new DocumentBuilder()
    .setTitle('My App')
    .setSchemes('https')
    .setDescription('My App API documentation')
    .setVersion('1.0')
    .build()

const document = SwaggerModule.createDocument(app, options)
SwaggerModule.setup('docs', app, document, {
    customSiteTitle: 'My App documentation',
})

// ...

有了这个选项,您将在/docs条路由中的任何一条上收到HTTP Basic Auth提示.为了保护Open/docs-json文件名,我们也需要显式生成JSON.

您不应该将凭据放在代码/存储库中,而应该放在.env中,并通过ConfigService进行访问.

我第一次看到这个解决方案是here.

Typescript相关问答推荐

为什么AB和CD这两种类型在TypScript中可以相互分配?

如何访问Content UI的DatePicker/中的sx props of year picker?'<>

对深度对象键/路径进行适当的智能感知和类型判断,作为函数参数,而不会触发递归类型限制器

如何使用函数填充对象?

如何在TypeScript中将一个元组映射(转换)到另一个元组?

如何在LucideAngular 添加自定义图标以及如何使用它们

TypeScrip-将<;A、B、C和>之一转换为联合A|B|C

带下拉菜单的Angular 响应式选项卡

有没有可能为这样的函数写一个类型?

为什么ESLint会抱怨函数调用返回的隐式`any`?

FatalError:Error TS6046:';--模块分辨率';选项的参数必须是:'; node ';,'; node 16';,'; node

有没有办法防止类型交集绕过联合类型限制?

使用Type脚本更新对象属性

如何使用泛型函数参数定义类型脚本函数

垫子工具栏不起作用的Angular 布线

类型判断数组或对象的isEmpty

为什么`map()`返回类型不能维护与输入相同数量的值?

Route.ts文件中未导出HTTP方法

将带有额外id属性的Rust struct 展平回TypeScript单个对象,以返回wasm-bindgen函数

我可以在 Typescript 中重用函数声明吗?