Search code examples
feathersjs

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


I thought to make a stack for my error now. I had some issues firing up authentication, but that was for my working project is a different version. I also had a problem with a different service and column naming convention then the default. Then it failed due to sequelize and mssql with the 'FETCH' 'NEXT' what I solved.

Environment

I am developing on a linux system. The database which is being used is currently on SQL2016. All selects are fine, and inserts/updates for before I enabled authentication I did stuff inserting/updating in the tables. Versions of the server and client

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

Issue

When I start a authentication on a client, which is set to strategy local, I get the error following bellow while I would expect to get 'authenticated' for the user and passord is correct.

Error

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

So offcourse some files are needed. First lets start with the backend side. I have several 'clusters' of services, so some code may need to shift.

file: ./app.js

This is the main application file. Here you also see how my user is created which I am using for testing.

'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;

file: ./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

This is the index file for the service. This is also where authentication is really configured for the data resides in this database.

'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
        }
    );
};

The configuration used in the file above is the following

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

file: ./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;
};

file: ./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: []
};

Next offcourse is the client. I have nuxtjs, but I also have a client which isn't nuxtjs and has the same issue. So I'm placing that for it's one file and easier for debugging.

'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);
});

If required I can expand this code, for I removed the stuff below this section which didn't help in solving it (irrelevent)

Request

Is it possible someone can point me in the right direction. Can it be I need to configure the custom fields still somewhere else? I tried searching for the issue to see if I can put something in 'errors:' but only found it seems to come from two files in 'feathers-authenticate' but I don't know where.

Solving

I'm thinking the issue is in having a part of the server setup in the 'index.js' of the services, and a part in the 'app.js' of the backend. Only I don't see yet where.

[20170612 1630] New files I made some adjustments to some files. Same result, but fits better. Does seem that a next step is not called though.

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 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;

file: ./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] Change in 'require' changes the error

I have changed the require for the authentication in './services/multifunctionalportal/index.js' from "require(./authentication/index)" to "require('feathers-authentication')" and now it gives and error about not finding the app.passport. And if authentication is configured before authentication local which it is.

[20170612 19:00] Moved configuration for authentication

So my config settings for the anthentication was in the 'index.js' of the service 'multifunctionalportal/authentication'. I moved that to the 'index.js' of the services it self and now that message is gone, but I now have a userless token. So if I enter a wrong password, it is still creating a token. If you look in the backend log, no user selection is appearing.

[20170612 20:00] In a loop

This last change is caused by missing hooks. The hooks for authentication currently are in the index.js of the authentication service. If I move them to the app.js then the problem is gone, and the message no authentication returns. So it does seem a configuration of some sort is not correct. Currently looking if I can prompt an error message in the 'messages' part of the initial error


Solution

  • Solution here was that the insert of a test user had the sequence 'user_password' 'user_name' and the login test was with 'user_name' 'user_password' I came accross this with a new user where the user/password was equal. When this user worked, I figured it out.

    The error doesn't say login failed due to incorrect password but when you do DEBUG=feathers-authentication* npm start it does show it.