【问题标题】:Using hapi-auth-basic使用 hapi-auth-basic
【发布时间】:2019-06-07 01:10:36
【问题描述】:

我曾尝试根据我找到的教程实施基本的身份验证策略。这就是我对server.js 文件的最终设置。

    'use strict';

const Hapi=require('hapi');
const sequelize = require('sequelize');
const models = require('./models');
const routes = require('./services/routes');
// Create a server with a host and port
const server=Hapi.server({
    host:'localhost',
    port:3100
});

// Add the route

server.register(require('hapi-auth-basic'), function (err) {

    if(err) {           throw err;        }

    server.auth.strategy('simple', 'basic', {
        validateFunc: function (username, password, callback) {

            if (username === 'admin') {
        return callback(null, true, {scope: 'admin'}); // They're an `admin 
            if (username === 'user') {
       return callback(null, true, {scope: 'user'}); // They're a `user`   }
            return callback(null, false);            }
    });
    server.route(routes);

// Start the server

    /*models.sequelize.sync().then( function () {*/


    const start = async function () {

        try {
            await server.start();
        }
        catch (err) {
            console.log(err);
            process.exit(1);
        }

        console.log('Server running at:', server.info.uri);
    };
    start();
    /*
    })*/
});

在运行npm start 时出现以下错误:

(node:7468) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝编号:1) (节点:7468)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

我对 node/hapi 真的很陌生,所以我不知道出了什么问题。我是否以正确的方式实施了身份验证策略?

【问题讨论】:

  • 首先,以上代码存在一些语法错误。在重现您的问题之前,我们需要进行一些修复。

标签: javascript node.js hapijs


【解决方案1】:
const Hapi = require("hapi");

const basicAuth = require("hapi-auth-basic");

const validate = async (request, username, password, h) => {
  if ("test" === username) {
    return { credentials: { name: "test 1" }, isValid: true };
  }
  return { credentials: null, isValid: false };
};

const main = async () => {
  const server = Hapi.server({ port: 4000 });

  // Register the plugin with hapi.
  await server.register(basicAuth);

  // Define strategy name and which method will use for validate the authorizatiion info.
  // "simple" is used as alias
  // "basic" the method for authorization is basic, it will ask user input username and password
  // "validate" the validation method it will be called when endpoint is called.
  server.auth.strategy("simple", "basic", { validate });

  // In case, we want all endpoints which need to be authorized, let enable below line.
  // Other wise, we need to set check authorization for each route manually.
  // server.auth.default("simple");

  // How to define a route without authorization.
  server.route({
    method: "GET",
    path: "/welcome",
    handler: function(request, h) {
      return "welcome";
    }
  });

  // How to define a route under authorization.
  server.route({
    method: "GET",
    path: "/admin",
    options: {
      auth: 'simple'
    },
    handler: function(request, h) {
      return "admin";
    }
  });

  await server.start();

  return server;
};

main()
  .then(server => console.log(`Server listening on ${server.info.uri}`))
  .catch(err => {
    console.error(err);
    process.exit(1);
  });

【讨论】:

【解决方案2】:

在某些项目中,我还添加了以下块来捕获未知错误或与 promise 相关的一些错误

process.on('unhandledRejection', error => {
  // eslint-disable-next-line no-process-exit
  process.exit(1);
});

process.on('uncaughtException', error => {
  logger.error(error.stack);
});

server.ext('onPreResponse', (request, h) => responseHandler(server, options, request, h));

responseHandler -> Is the method for parsing error to a starndard format.

【讨论】:

    猜你喜欢
    • 2016-02-22
    • 1970-01-01
    • 2014-08-24
    • 2014-10-10
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    相关资源
    最近更新 更多