feathersjs - >错误401,消息“错误”和NotAuthenticated

时间:2017-06-12 13:02:27

标签: feathersjs

我想现在为我的错误做一个堆栈。我有一些问题引发认证,但那是我的工作项目是一个不同的版本。我也遇到了不同的服务和列命名约定的问题,然后是默认值。然后由于sequelize和mssql与'FETCH''NEXT'失败了,我解决了。

环境

我正在开发一个Linux系统。正在使用的数据库当前在SQL2016上。所有选择都很好,并且在我启用身份验证之前插入/更新我在表中进行了插入/更新。服务器和客户端的版本

Server
    "feathers": "^2.1.1",
    "feathers-authentication": "^1.2.1",
    "feathers-authentication-jwt": "^0.3.1",
    "feathers-authentication-local": "^0.3.4",
    "feathers-configuration": "^0.3.3",
    "feathers-errors": "^2.6.2",
    "feathers-hooks": "^1.8.1",
    "feathers-rest": "^1.7.1",
    "feathers-sequelize": "^1.4.5",
    "feathers-socketio": "^1.5.2",

Client
    "feathers": "^2.1.2",
    "feathers-authentication": "^1.2.4",
    "feathers-authentication-client": "^0.3.2",
    "feathers-client": "^2.2.0",
    "feathers-localstorage": "^1.0.0",
    "feathers-socketio": "^2.0.0",

问题

当我在设置为策略本地的客户端上启动身份验证时,我得到以下错误,而我希望为用户获得“身份验证”并且密码是正确的。

错误

  Error authenticating! { type: 'FeathersError',
  name: 'NotAuthenticated',
  message: 'Error',
  code: 401,
  className: 'not-authenticated',
  errors: {} }

所以当然需要一些文件。首先让我们从后端开始。我有几个“集群”服务,所以有些代码可能需要转移。

file:./ app.js

这是主要的应用程序文件。在这里,您还可以看到我的用户是如何创建的,用于测试。

'use strict';

const path = require('path');
const serveStatic = require('feathers').static;
const favicon = require('serve-favicon');
const compress = require('compression');
const cors = require('cors');
const feathers = require('feathers');
const configuration = require('feathers-configuration');
const authentication = require('feathers-authentication');
const jwt = require('feathers-authentication-jwt');
const local = require('feathers-authentication-local');
const hooks = require('feathers-hooks');
const rest = require('feathers-rest');
const bodyParser = require('body-parser');
const socketio = require('feathers-socketio');
const middleware = require('./middleware');
const servicesMfp = require('./services/A');
const servicesMic = require('./services/B');

const app = feathers();

app.configure(configuration(path.join(__dirname, '..')));

app.use(compress())
    .options('*', cors())
    .use(cors())
    .use(favicon(path.join(app.get('public'), 'favicon.ico')))
    .use('/', serveStatic(app.get('public')))
    .use(bodyParser.json())
    .use(bodyParser.urlencoded({extended: true}))
    .configure(hooks())
    .configure(rest())
    .configure(socketio())
    .configure(servicesMfp)
    .configure(servicesMic)
    .configure(middleware)
    .configure(local({
        usernameField: 'user_name',
        passwordField: 'user_password'
    }))
    .configure(jwt());

app.service('/mfp/authentication').hooks({
    before: {
        create: [
            authentication.hooks.authenticate(['jwt', 'local']),
        ],
        remove: [
            authentication.hooks.authenticate('local')
        ]
    }
});

/*
const userService = app.service('/mfp/sys_users');
const User = {
    user_email: 'ekoster3@mail.com',
    user_password: 'ekoster',
    user_name: 'ekoster2',
    status_id: 1
};
userService.create(User, {}).then(function(user) {
    console.log('Created default user', user);
});
*/

module.exports = app;

档案:./ services /multifunctionalportal / authentiction / index.js

'use strict';

const authentication = require('feathers-authentication');

module.exports = function () {
    const app = this;
    let config = app.get('mfp_auth');

    app.configure(authentication(config));
};

file:./ services /multifunctionalportal / sys_user / index.js

这是服务的索引文件。这也是为此数据库中的数据实际配置身份验证的地方。

'use strict';
const authentication = require('./authentication/index');
const sys_user = require('./sys_user/index');
const sys_metadata = require('./sys_metadata/index');
const sys_term = require('./sys_term');
const sys_source = require('./sys_source/index');
const sys_source_user = require('./sys_source_user/index');
const survey = require('./survey/index');
const survey_question = require('./survey_question/index');
const Sequelize = require('sequelize');

module.exports = function () {
    const app = this;

    //TODO make it more cross DB (different dbtypes)
    const sequelize = new Sequelize(app.get('mfp_db_database'), app.get('mfp_db_user'), app.get('mfp_db_password'), {
        host: app.get('mfp_db_host'),
        port: app.get('mfp_db_port'),
        dialect: 'mssql',
        logging: true,
        dialectOptions: {
            instanceName: app.get('mfp_db_instance')
        }
    });
    app.set('mfp_sequelize', sequelize);

    app.configure(authentication);
    app.configure(sys_user);
    app.configure(sys_metadata);
    app.configure(sys_term);
    app.configure(sys_source);
    app.configure(sys_source_user);
    app.configure(survey);
    app.configure(survey_question);

    Object.keys(sequelize.models).forEach(function(modelName) {
        if ("associate" in sequelize.models[modelName]) {
            sequelize.models[modelName].associate();
        }
    });

    sequelize.sync(
        {
            force: false
        }
    );
};

上述文件中使用的配置如下

"mfp_auth": {
        "path": "/mfp/authentication",
        "service": "/mfp/sys_users",
        "entity": "sys_user",
        "strategies": [
            "local",
            "jwt"
        ],
        "secret": "WHO_KNOWS"
    }

文件:./ services /multifunctionalportal / sys_user / sys_user-model.js

'use strict';

const Sequelize = require('sequelize');

module.exports = function (sequelize) {
    const sys_user = sequelize.define('sys_users', {
        user_email: {
            type: Sequelize.STRING(256),
            allowNull: false,
            unique: true
        },
        user_name: {
            type: Sequelize.STRING(256),
            allowNull: false,
            unique: true
        },
        user_password: {
            type: Sequelize.STRING(256),
            allowNull: false
        },
        status_id: {
            type: Sequelize.INTEGER,
            allowNull: false
        }
    }, {
        freezeTableName: true,
        paranoid: true,
        timestamps  : true,
        underscored : true,
        classMethods: {
            associate() {
                sys_user.belongsTo(sequelize.models.sys_metadata, {
                    allowNull: false,
                    as: 'status'
                });
                sys_user.hasMany(sequelize.models.sys_source_users, {
                    as: 'user',
                    foreignKey: 'user_id',
                    targetKey: 'user_id',
                    onDelete: 'no action'
                });
            }
        }
    });

    sys_user.sync();

    return sys_user;
};

档案:./ services /multifunctionalportal / sys_user / hook / index.js

'use strict';

const globalHooks = require('../../../../hooks');
const hooks = require('feathers-hooks');
const authentication = require('feathers-authentication');
const local = require('feathers-authentication-local');

exports.before = {
    all: [],
    find: [
        authentication.hooks.authenticate('jwt')
    ],
    get: [],
    create: [
        local.hooks.hashPassword({ passwordField: 'user_password' })
    ],
    update: [],
    patch: [],
    remove: []
};

exports.after = {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
};

接下来就是客户。我有nuxtjs,但我也有一个不是nuxtjs的客户端,并且有同样的问题。所以我把它放在一个文件中,更容易调试。

'use strict';
const feathers = require('feathers/client');
const socketio = require('feathers-socketio/client');
const hooks = require('feathers-hooks');
const io = require('socket.io-client');
const authentication = require('feathers-authentication-client');
const localstorage = require('feathers-localstorage');
const process = require('../../config');
const winston = require('winston');
const tslog = () => (new Date()).toLocaleTimeString();

const mfpSocket = io(process.env.backendUrl);
const mfpFeathers = feathers()
    .configure(socketio(mfpSocket))
    .configure(hooks())
    .configure(authentication());

const surveyLog = new (winston.Logger)({
    transports: [
        new (winston.transports.Console)({
            timestamp: tslog,
            colorize: true
        }),
        new (require('winston-daily-rotate-file'))({
            filename: process.env.logDirectory + '/-' + process.env.logFileSurvey,
            timestamp: tslog,
            datePattern: 'yyyyMMdd',
            prepend: true,
            level: process.env.logLevelSurvey
        })
    ]
});


//TODO login then continue
mfpFeathers.authenticate({
    strategy: 'local',
    'user_name': 'ekoster',
    'user_password': 'ekoster2'
}).then(function(result){
    console.log('Authenticated!', result);
}).catch(function(error){
    console.error('Error authenticating!', error);
});

如果需要,我可以扩展此代码,因为我删除了本节下面的内容,这些内容无法解决问题(无关紧要)

请求

是否有人可以指出我正确的方向。是否我需要在其他地方配置自定义字段?我试着搜索问题,看看我是否可以在“错误:”中添加一些东西,但只发现它似乎来自'羽毛 - 验证'中的两个文件,但我不知道在哪里。

解决

我认为问题在于服务的'index.js'中的服务器设置的一部分,以及后端的'app.js'中的一部分。只有我还没有看到。

[20170612 1630]新文件 我对一些文件做了一些调整。结果相同,但更适合。似乎没有调用下一步。

文件:app.js

'use strict';

const path = require('path');
const serveStatic = require('feathers').static;
const favicon = require('serve-favicon');
const compress = require('compression');
const cors = require('cors');
const feathers = require('feathers');
const configuration = require('feathers-configuration');
const hooks = require('feathers-hooks');
const rest = require('feathers-rest');
const bodyParser = require('body-parser');
const socketio = require('feathers-socketio');
const middleware = require('./middleware');
const servicesMfp = require('./services/multifunctionalportal');
const servicesMic = require('./services/mexonincontrol');

const app = feathers();

app.configure(configuration(path.join(__dirname, '..')));

app.use(compress())
    .options('*', cors())
    .use(cors())
    .use(favicon(path.join(app.get('public'), 'favicon.ico')))
    .use('/', serveStatic(app.get('public')))
    .use(bodyParser.json())
    .use(bodyParser.urlencoded({extended: true}))
    .configure(hooks())
    .configure(rest())
    .configure(socketio())
    .configure(servicesMfp)
    .configure(servicesMic)
    .configure(middleware);

/*
const userService = app.service('/mfp/sys_users');
const User = {
    user_email: 'ekoster3@mexontechnology.com',
    user_password: 'ekoster',
    user_name: 'ekoster2',
    status_id: 1
};
userService.create(User, {}).then(function(user) {
    console.log('Created default user', user);
});
*/

module.exports = app;

档案:./ services /multifunctionalportal / index.js

'use strict';
const authentication = require('./authentication/index');
const jwt = require('feathers-authentication-jwt');
const local = require('feathers-authentication-local');
const sys_user = require('./sys_user/index');
const sys_metadata = require('./sys_metadata/index');
const sys_term = require('./sys_term');
const sys_source = require('./sys_source/index');
const sys_source_user = require('./sys_source_user/index');
const survey = require('./survey/index');
const survey_question = require('./survey_question/index');
const Sequelize = require('sequelize');

module.exports = function () {
    const app = this;

    //TODO make it more cross DB (different dbtypes)
    const sequelize = new Sequelize(app.get('mfp_db_database'), app.get('mfp_db_user'), app.get('mfp_db_password'), {
        host: app.get('mfp_db_host'),
        port: app.get('mfp_db_port'),
        dialect: 'mssql',
        logging: true,
        dialectOptions: {
            instanceName: app.get('mfp_db_instance')
        }
    });
    app.set('mfp_sequelize', sequelize);

    app.configure(authentication);
    app.configure(local({
        usernameField: 'user_name',
        passwordField: 'user_password'
    }));
    app.configure(jwt());
    app.configure(sys_user);
    app.configure(sys_metadata);
    app.configure(sys_term);
    app.configure(sys_source);
    app.configure(sys_source_user);
    app.configure(survey);
    app.configure(survey_question);

    Object.keys(sequelize.models).forEach(function(modelName) {
        if ("associate" in sequelize.models[modelName]) {
            sequelize.models[modelName].associate();
        }
    });

    sequelize.sync(
        {
            force: false
        }
    );
};

file:./ services /multifunctionalportal /authentication / index.js

'use strict';
const authentication = require('feathers-authentication');

module.exports = function () {
    const app = this;
    const config = app.get('mfp_auth');
    const authService = app.service('/mfp/authentication');

    app.configure(authentication(config));

    authService.before({
        create: [
            authentication.hooks.authenticate(['jwt', 'local']),
        ],
        remove: [
            authentication.hooks.authenticate('local')
        ]
    });
};

[20170612 16:45]更改'require'会更改错误

我已将“./services/multifunctionalportal/index.js”中的身份验证要求从“require(./ authentication / index)”更改为“require('feathers-authentication')”,现在它给出了关于找不到app.passport的错误。如果在身份验证之前配置了身份验证,那么它就是。

[20170612 19:00]移动了身份验证配置

因此,我的身份验证配置设置位于服务'多功能门户/身份验证'的'index.js'中。我将它移动到它自己的服务的'index.js',现在消息已经消失,但我现在有一个无用户令牌。因此,如果我输入了错误的密码,它仍然会创建一个令牌。如果查看后端日志,则不会显示任何用户选择。

[20170612 20:00]循环

最后一次更改是由缺少钩子引起的。用于身份验证的挂钩当前位于身份验证服务的index.js中。如果我将它们移动到app.js然后问题就消失了,并且消息没有验证返回。所以它看起来似乎某种配置是不正确的。目前正在查看是否可以在初始错误的“消息”部分中提示错误消息

1 个答案:

答案 0 :(得分:0)

这里的解决方案是,测试用户的插入具有序列'user_password''user_name',并且登录测试使用'user_name''user_password'我与用户/密码相等的新用户相遇。当这个用户工作时,我想通了。

错误并不表示由于密码错误导致登录失败,但当您执行DEBUG=feathers-authentication* npm start时,它确实显示了该错误。