【问题标题】:Getting authentication error with HapiJS使用 HapiJS 获取身份验证错误
【发布时间】:2015-10-17 23:51:44
【问题描述】:

我创建了这个简单的插件:

import bcrypt from 'bcrypt';
import Joi from 'joi';

import DynamoDBClient from '../lib/DynamoDBClient';

exports.register = (server, options, next) => {
  server.auth.strategy('simple', 'basic', {
    validateFunc: (request, email, password, callback) => {
      DynamoDBClient.findUserByEmail(email)
        .then(user => {
          if (!user) {
            return callback(null, false);
          }

          bcrypt.compare(password, user.password, (err, isValid) => {
            return callback(err, isValid, { id: user.id });
          });
        });
    }
  });

  server.route({
    method: 'POST',
    path: '/api/login',
    config: {
      auth: 'simple',
      validate: {
        payload: {
          email: Joi.string().required(),
          password: Joi.string().required()
        }
      }
    },
    handler: (request, reply) => reply(request.auth.credentials.id)
  });

  next();
};

exports.register.attributes = {
  name: 'login',
};

并在此处加载清单:

import Glue from 'glue';

const manifest = {
  server: {},
  connections: [
    {
      port: process.env.PORT || 3001,
      labels: ['api']
    }
  ], 
  plugins: {
    'hapi-auth-basic': {}, 
    './api/signup': {},
    './api/login': {},
    './api/products': {},
  }
};

const options = {
  relativeTo: __dirname
};

Glue.compose(manifest, options, (err, server) => {
  if (err) {
    throw err;
  }

  server.start(() => console.log(`Listening to ${server.info.uri}`));
});

但我收到此错误

{
  "statusCode": 401,
  "error": "Unauthorized",
  "message": "Missing authentication"
}

当我尝试使用电子邮件和密码作为正文参数的 POST 请求登录时。

【问题讨论】:

    标签: javascript node.js authentication hapijs


    【解决方案1】:

    我认为您的 /api/login 路由不应受到身份验证方案的保护,否则,您必须经过身份验证才能进行身份验证。鸡和蛋的问题......你所有的其他路线都应该是。

    换句话说,登录(和注销?)路由不应该是安全的。

    【讨论】:

    • 有道理,但如果我不保护该来源,我应该保护哪个来源?从那里删除身份验证禁用身份验证并且凭据对象为空
    • 我认为您应该保护 API 的其余部分。我从来没有写过自己的策略:主要是我使用 hapi-auth-cookie 和我自己的验证功能。这里有一个最近的教程medium.com/@poeticninja/… 可能会对您有所帮助。简而言之,如果您想自己做,我认为您需要在 /api/login 中完成身份验证时以某种方式设置会话,然后在其他路由中检查该会话。
    猜你喜欢
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    相关资源
    最近更新 更多