【问题标题】:How to put authentication on hapi-swagger documentation page so that only authentic user could see my documentation如何在 hapi-swagger 文档页面上进行身份验证,以便只有真实用户才能看到我的文档
【发布时间】:2017-01-30 12:07:56
【问题描述】:

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

【问题讨论】:

  • 我有同样的问题,即使我很长时间以来都被这个问题所困扰。为什么不直接联系 github 上的开发人员?

标签: node.js authentication swagger basic-authentication hapijs


【解决方案1】:
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();

【讨论】:

    【解决方案2】:

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

    例如。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-23
      • 2016-08-20
      • 2021-04-05
      • 2020-06-22
      • 1970-01-01
      • 2015-03-16
      • 2018-03-19
      • 2015-05-11
      相关资源
      最近更新 更多