Skip to content

Error format #1262

Closed
Closed

Description

@PowerMogli

Steps to reproduce

We are using @feathersjs/feathers version 3.1.3 with @feathersjs/errors version 3.3.0.

We configure authentication service with some hooks:

app.service('authentication').hooks(authHooks(app));

function authHooks(app) {
  const config = app.get('authentication');
  return {
    before: {
      create: [validateUserAccess, authentication.hooks.authenticate(config.strategies)],
      remove: [authentication.hooks.authenticate('jwt')],
    },
  };
}

When we throw a Forbidden error object inside the validateUserAccess hook then we get a json object back (called by rest&ws). When we throw a Forbidden error object inside service hook we get html back without error code (rest&ws). Why is that?

We would like to get the same json output for hooks before service calls and hooks for authentication.

Activity

  1. daffl commented on Mar 29, 2019

    @daffl
    Member

    The error format is determined by the client request by setting the Accept header. For JSON it should be application/json and then you should get back what you are expecting.

  2. PowerMogli commented on Mar 29, 2019

    @PowerMogli
    Author

    I am sorry but that did not the trick. We still receive html.

  3. daffl commented on Mar 29, 2019

    @daffl
    Member

    What is your setup? Did you configure the error handler?

  4. PowerMogli commented on Mar 29, 2019

    @PowerMogli
    Author
    import { factory, mongodb } from '@alberta/konexi-api-shared';
    import feathersSync = require('@bitscheme/feathers-sync');
    import configuration = require('@feathersjs/configuration');
    import express = require('@feathersjs/express');
    import feathers = require('@feathersjs/feathers');
    import socketio = require('@feathersjs/socketio');
    import compress = require('compression');
    import cors = require('cors');
    import helmet = require('helmet');
    
    import { hooks } from './app.hooks';
    import authentication from './authentication';
    import { channels } from './channels';
    import { discovery } from './discovery';
    import { services } from './services';
    
    const app = express.default(feathers.default());
    
    app.configure(configuration());
    
    app.set('logger', factory(app.get('service')));
    
    app.use(cors());
    app.use(helmet());
    app.use(compress());
    app.use(express.json({ limit: '100mb' }));
    app.use(express.urlencoded({ limit: '100mb', extended: true }));
    app.configure(express.rest());
    app.configure(
      socketio.default(
        {
          allowUpgrades: false,
          serveClient: false,
          transports: ['websocket'],
          pingInterval: 40000,
        },
        io => {
          io.use((socket, next) => {
            (socket as any).feathers.connection_id = socket.id;
            next();
          });
        },
      ),
    );
    app.configure(mongodb);
    app.configure(authentication);
    app.configure(discovery);
    app.configure(services);
    app.configure(channels);
    app.use(express.errorHandler());
    
    app.get('mongoClient').then(client => {
      app.configure(
        feathersSync.mongodb({
          db: client.db('sync'),
          collection: 'sync',
        }),
      );
    });
    
    app.hooks(hooks);
    
    export default app;
  5. daffl commented on Mar 29, 2019

    @daffl
    Member

    And what's the code for when you are getting the right error and when not?

  6. PowerMogli commented on Mar 29, 2019

    @PowerMogli
    Author

    This is when right error:

    import authentication = require('@feathersjs/authentication');
    import jwt = require('@feathersjs/authentication-jwt');
    import local = require('@feathersjs/authentication-local');
    
    import apikey from './auth-strategies/apikey';
    import { authHooks } from './hooks/auth-hooks';
    
    export default function(app) {
      const config = app.get('authentication');
    
      // Set up authentication with the secret
      app.configure(authentication.default(config));
      app.configure(jwt.default());
      app.configure(local.default());
      app.configure(apikey({ header: config.apiKey.header }));
      // The `authentication` service is used to create a JWT.
      // The before `create` hook registers strategies that can be used
      // to create a new valid JWT (e.g. local or oauth2)
      app.service('authentication').hooks(authHooks(app));
    }

    inside ./hooks/auth-hooks:

    export function authHooks(app) {
      const config = app.get('authentication');
      return {
        before: {
          create: [validateUserAccess, authentication.hooks.authenticate(config.strategies)],
          remove: [authentication.hooks.authenticate('jwt')],
        },
      };
    }
    
    const validateUserAccess = async (context: HookContext<any>) => {
      const userService = context.app.service('users');
      const config = context.app.get('authentication');
      const users = await userService.find({
        query: {
          [config.local.usernameField]: context.data[`${config.local.usernameField}`],
          $limit: 1,
        },
      });
    
      if (users && users.length && typeof users[0].active === 'boolean' && !users[0].active) {
        throw new Forbidden('You don`t have the permission to execute the requested operation.');
      }
    
      return context;
    };

    when not:

    const validateUserAccess = async (context: HookContext<any>) => {
      const {
        params: { user },
      } = context;
    
      if (typeof user.active === 'boolean' && !user.active) {
        throw new Forbidden('You don`t have the permission to execute the requested operation.');
      }
    
      return context;
    };
    
    export function registerRoute(app: Application<any>, route: IRoute) {
      app.use(`/${route.apiRoute}`, new Proxy(route.apiRoute, route.upstreamUrl, route.customEvents));
      const proxy = app.service(route.apiRoute);
      proxy.hooks({
        before: {
          all: [
            commonHooks.paramsFromClient('apiKey', 'accessToken', 'changes', 'authorization', 'fromExternalApi'),
            ctx => {
              const config = ctx.app.get('authentication');
              if (ctx.params.accessToken) {
                ctx.params.headers = { ...ctx.params.headers, authorization: ctx.params.accessToken };
              }
              if (ctx.params.headers && !ctx.params.headers.hasOwnProperty(config.apiKey.header)) {
                ctx.params.headers[config.apiKey.header] = ctx.params.apiKey;
              }
            },
            authenticate(),
            populateAuthUser(),
            commonHooks.iff(ctx => ctx.params.fromExternalApi, populateUserWithAuthorization()),
          ],
          find: [validateUserAccess, validatePermission(Permission.Synchronize)],
          create: [validateUserAccess, validatePermission(Permission.Write)],
          patch: [validateUserAccess, validatePermission(Permission.Write), changeTrackerLog(), changeTrackerWriteDb()],
        },
      });
    }
  7. PowerMogli commented on Mar 29, 2019

    @PowerMogli
    Author

    I am sorry that is all I can answer for. I hope it is enough to find out the issue.

  8. KidkArolis commented on Mar 29, 2019

    @KidkArolis
    Contributor

    Could you put a breakpoint or console.log(req.headers) on node_modules/@feathersjs/errors/lib/error-handler.js#97 to show us what headers the request is receiving in both cases?

  9. PowerMogli commented on Apr 1, 2019

    @PowerMogli
    Author

    The breakpoint for html response never gets hit in error-handler.js

    The error code goes the following path:
    node_modules/@feathersjs/express/lib/rest/wrapper.js#84 then node_modules/express/lib/router/route.js#135 and finally node_modules/express/lib/router/layer.js#67

    In case of authentication create request your breakpoint gets hit but not in my second case I mentioned above.

    We also get html back when authentication fails because of invalid jwt. Even so we set header Accept to application/json.

    For all our tests we are using Postman.

  10. added this to the v5 (Dove) milestone on Mar 18, 2021
  11. DattaramNaik commented on Aug 29, 2023

    @DattaramNaik

    I am using feather js backend ....

    I am getting error response in html format

    <title>Error</title>
                NotAuthenticated: Invalid login
      at LocalStrategy.findEntity (D:\pracup\Pracup Devlopment\pracup_backend\node_modules\@feathersjs\authentication-local\lib\strategy.js:60:19)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async LocalStrategy.authenticate (D:\pracup\Pracup Devlopment\pracup_backend\node_modules\@feathersjs\authentication-local\lib\strategy.js:105:24)
      at async AuthenticationService.create (D:\pracup\Pracup Devlopment\pracup_backend\node_modules\@feathersjs\authentication\lib\service.js:82:28)
      at async AuthenticationService.<anonymous >(D:\pracup\Pracup Devlopment\pracup_backend\node_modules\@feathersjs\authentication\lib\hooks\connection.js:4:5)
      at async AuthenticationService.<anonymous >(D:\pracup\Pracup Devlopment\pracup_backend\node_modules\@feathersjs\authentication\lib\hooks\event.js:6:5)
      at async AuthenticationService.<anonymous >(D:\pracup\Pracup Devlopment\pracup_backend\node_modules\@feathersjs\schema\lib\hooks\resolve.js:115:5)
      at async AuthenticationService.logError (file:///D:/pracup/Pracup%20Devlopment/pracup_backend/src/hooks/log-error.js:5:5)
      at async D:\pracup\Pracup Devlopment\pracup_backend\node_modules\@feathersjs\express\lib\rest.js:33:25

    I want json format

    I am sending application/json through client still getting html response .

  12. daffl commented on Aug 31, 2023

    @daffl
    Member

    When submitted from the browser, it will always prefer HTML. You can disable HTML responses completely with the { html: false } option

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions