feathersjs -> 错误 401 消息 'Error' 和 NotAuthenticated

feathersjs -> Error 401 with message 'Error' and NotAuthenticated

我现在想为我的错误做一个堆栈。我在启动身份验证时遇到了一些问题,但那是因为我的工作项目是不同的版本。我还遇到了与默认设置不同的服务和列命名约定的问题。然后由于我解决的 'FETCH' 'NEXT' sequelize 和 mssql 而失败。

环境

我正在 linux 系统上开发。正在使用的数据库当前在 SQL2016 上。所有选择都很好,inserts/updates 因为在我启用身份验证之前,我在表中做了一些事情 inserting/updating。服务器和客户端的版本

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",

问题

当我在设置为本地策略的客户端上启动身份验证时,出现以下错误,而我希望为用户获得 'authenticated',密码正确。

错误

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

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

文件:./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));
};

文件:./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/hooks/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);
});

如果需要我可以扩展这段代码,因为我删除了这部分下面的内容,这些内容对解决问题没有帮助(无关紧要)

请求

是否有人可以为我指明正确的方向。难道我还需要在其他地方配置自定义字段吗?我试着搜索这个问题,看看我是否可以在 'errors:' 中添加一些东西,但只发现它似乎来自 'feathers-authenticate' 中的两个文件,但我不知道在哪里。

求解

我认为问题在于在服务的 '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
        }
    );
};

文件:./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')",现在它给出了关于找不到[=140=的错误].并且如果在认证本地之前配置了认证。

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

所以我的验证配置设置在服务 'multifunctionalportal/authentication' 的 'index.js' 中。我将它移到了它自己的服务的 'index.js' 中,现在该消息消失了,但我现在有了一个无用户令牌。因此,如果我输入了错误的密码,它仍然会创建一个令牌。如果您查看后端日志,没有出现用户选择。

[20170612 20:00]在循环中

最后的更改是由于缺少挂钩造成的。当前用于身份验证的挂钩位于身份验证服务的 index.js 中。如果我将它们移动到 app.js 那么问题就消失了,并且消息没有验证 returns。所以看起来某种配置确实不正确。目前正在寻找是否可以在初始错误

的'messages'部分提示错误信息

这里的解决方案是测试用户的插入序列为 'user_password' 'user_name' 并且登录测试是 'user_name' 'user_password' user/password 相等的新用户。当这个用户工作时,我想通了。

错误并没有说由于密码错误导致登录失败,但是当您这样做时 DEBUG=feathers-authentication* npm start 它确实显示了。