Feathersjs - ›Ошибка 401 с сообщением" Ошибка "и NotAuthenticated.

Думал сейчас сделать стек за свою ошибку. У меня были проблемы с запуском аутентификации, но для моего рабочего проекта это была другая версия. У меня также была проблема с другим соглашением об именах служб и столбцов, чем по умолчанию. Затем это не удалось из-за 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: {} }

Так что, конечно, нужны файлы. Сначала давайте начнем с серверной части. У меня есть несколько «кластеров» сервисов, поэтому может потребоваться сдвиг некоторого кода.

файл: ./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: '[email protected]',
    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);
});

При необходимости я могу расширить этот код, так как я удалил вещи под этим разделом, которые не помогли в его решении (не имеет значения)

Запрос

Может ли кто-нибудь указать мне правильное направление? Может быть, мне нужно настроить настраиваемые поля еще где-нибудь? Я попытался найти проблему, чтобы узнать, могу ли я что-то добавить в «ошибки:», но обнаружил, что она, кажется, исходит из двух файлов в «перья-аутентификации», но я не знаю, где.

Решение

Я думаю, проблема в том, что часть настройки сервера находится в 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: '[email protected]',
    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] Изменение параметра "Требовать" изменяет ошибку.

Я изменил требование для аутентификации в './services/multifunctionalportal/index.js' с "require (./ authentication / index)" на "require ('pens-authentication')", и теперь он выдает ошибку о том, что нет нахождение апп. паспорта. И если аутентификация настроена до аутентификации локальная, то она и есть.

[20170612 19:00] Конфигурация для аутентификации перенесена.

Таким образом, мои настройки конфигурации для проверки подлинности были в index.js службы «многофункциональный портал / проверка подлинности». Я переместил это в index.js самих сервисов, и теперь это сообщение исчезло, но теперь у меня есть токен без пользователя. Поэтому, если я введу неправильный пароль, токен все равно будет создаваться. Если вы посмотрите в бэкэнд-журнал, пользовательский выбор не появится.

[20170612 20:00] В цикле

Это последнее изменение вызвано отсутствием крючков. Перехватчики для аутентификации в настоящее время находятся в index.js службы аутентификации. Если я перенесу их в app.js, проблема исчезнет, ​​и сообщение об отсутствии аутентификации вернется. Так что кажется, что какая-то конфигурация неверна. Сейчас ищу, могу ли я запросить сообщение об ошибке в части «сообщения» исходной ошибки.


person Edgar Koster    schedule 12.06.2017    source источник
comment
Можете ли вы поместить свой ломающийся репозиторий где-нибудь на GitHub или BitBucket, чтобы воспроизвести ошибку? Такой объем кода трудно понять в вопросе SO.   -  person Daff    schedule 13.06.2017


Ответы (1)


Решение здесь заключалось в том, что вставка тестового пользователя имела последовательность 'user_password' 'user_name', а тест входа был с 'user_name' 'user_password'. Я столкнулся с этим с новым пользователем, у которого пользователь / пароль были равны. Когда этот пользователь работал, разобрался.

Ошибка не говорит о том, что вход в систему не удался из-за неправильного пароля, но когда вы делаете DEBUG=feathers-authentication* npm start, он показывает это.

person Edgar Koster    schedule 13.06.2017