我正在使用 hapi-swagger 制作API,并且我已经实现了基本身份验证。但即使用户没有身份验证,他仍然可以查看我的文档页面。我想阻止他查看我的文档页面。如何在swagger文档页面上实现基本身份验证? I want to hide this page and ask for authentication credentials before rendering documentation
答案 0 :(得分: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();
答案 1 :(得分:0)
您需要在插件注册时设置属性 auth
。
例如
await server.register([
{
plugin: require('hapi-swagger'),
options: {
auth: 'my-oauth-strategy',
}
}]);