是否可以添加身份验证以访问NestJS&39;Swagger Explorer [英] Is it possible to add Authentication to access to NestJS' Swagger Explorer

查看:7
本文介绍了是否可以添加身份验证以访问NestJS&39;Swagger Explorer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前在我的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中访问资源管理器,这正是我所期望的。但我想知道是否可以向浏览器添加任何身份验证层,以便只接受某些请求。

我希望使此资源管理器可在生产中访问,但仅供经过身份验证的用户访问。

提前感谢:)

推荐答案

使用带有Express的NestJS保护对Swagger的访问

首先运行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提示。我们还必须显式命名/docs-json,以保护生成的JSON OpenAPI文件。

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

我首先看到了此解决方案here

这篇关于是否可以添加身份验证以访问NestJS&39;Swagger Explorer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆