如何在 hapi-swagger 文档页面上进行身份验证,以便只有真实的用户才能看到我的文档

问题描述 投票:0回答:3

我正在使用 hapi-swagger 制作 API,并且我已经实现了基本身份验证。但即使用户没有身份验证,他仍然可以查看我的文档页面。我想阻止他查看我的文档页面。如何在 swagger 文档页面上实现基本身份验证? I want to hide this page and ask for authentication credentials before rendering documentation

node.js authentication swagger basic-authentication hapi.js
3个回答
0
投票
const Hapi = require('@hapi/hapi');
const basicAuth = require('basic-auth');
const server = new Hapi.server({ port: process.env.port || 3005, host: "localhost" });
server.ext('onRequest', (req, h) => {

    const route = req.url.pathname;
    if (route === "/documentation") {
        let user = basicAuth(req);
        if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'pwd') {
            return h.response("Unauthorized")
                .code(401)
                .header('WWW-Authenticate', 'Basic realm="Node"')
                .takeover()

        }
    }


    return h.continue;
});
const startServer = async () => {
    await server.register([
        require('@hapi/vision'),
        require('@hapi/inert'),
        {
            plugin: require('hapi-swagger'),
            options: {
                info: {
                    title: 'Doc',
                },
                schemes: ["http", "https"],
                securityDefinitions: {},
                security: [],

            }
        }]);
    await server.start();
    console.log(`Server running at: ${server.info.uri}`);
};

process.on('unhandledRejection', (err) => {
    console.error(err);
    console.error(err.stack);
    process.exit(1);
});
startServer();

0
投票

您需要在插件注册时设置属性

auth

例如。

    await server.register([
        {
            plugin: require('hapi-swagger'),
            options: {
                auth: 'my-oauth-strategy',
            }
        }]);

0
投票

您需要在插件注册时设置属性身份验证。

例如。

await server.register([
    {
        plugin: require('hapi-swagger'),
        options: {
           auth: 'my-oauth-strategy',
       }
  }]);

我无法理解

auth
文档中的选项工作。

如果您的 API 已经有身份验证协议和功能,如何将它们集成到 hapi-swagger 和 swagger-ui 中?

假设您的端点使用在特定标头中发送的令牌,如何将相同的逻辑添加到文档端点?在回复文档之前是否可以对请求及其上下文运行一个函数?

© www.soinside.com 2019 - 2024. All rights reserved.