使用HapiJS获取身份验证错误

时间:2015-10-17 11:51:20

标签: javascript node.js authentication hapijs

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

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请求。

1 个答案:

答案 0 :(得分:1)

我认为您的{latitude: 123, longitude: 321, distance: 543}路由不应受身份验证方案的保护,否则您必须通过身份验证才能进行身份验证。鸡肉和鸡蛋问题......你所有的其他路线应该是。

换句话说,登录(以及类似注销?)路由不应该受到保护。