You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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.
importauthentication= require('@feathersjs/authentication');importjwt= require('@feathersjs/authentication-jwt');importlocal= require('@feathersjs/authentication-local');importapikeyfrom'./auth-strategies/apikey';import{authHooks}from'./hooks/auth-hooks';exportdefaultfunction(app){constconfig=app.get('authentication');// Set up authentication with the secretapp.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:
exportfunctionauthHooks(app){constconfig=app.get('authentication');return{before: {create: [validateUserAccess,authentication.hooks.authenticate(config.strategies)],remove: [authentication.hooks.authenticate('jwt')],},};}constvalidateUserAccess=async(context: HookContext<any>)=>{constuserService=context.app.service('users');constconfig=context.app.get('authentication');constusers=awaituserService.find({query: {[config.local.usernameField]: context.data[`${config.local.usernameField}`],$limit: 1,},});if(users&&users.length&&typeofusers[0].active==='boolean'&&!users[0].active){thrownewForbidden('You don`t have the permission to execute the requested operation.');}returncontext;};
when not:
constvalidateUserAccess=async(context: HookContext<any>)=>{const{params: { user },}=context;if(typeofuser.active==='boolean'&&!user.active){thrownewForbidden('You don`t have the permission to execute the requested operation.');}returncontext;};exportfunctionregisterRoute(app: Application<any>,route: IRoute){app.use(`/${route.apiRoute}`,newProxy(route.apiRoute,route.upstreamUrl,route.customEvents));constproxy=app.service(route.apiRoute);proxy.hooks({before: {all: [commonHooks.paramsFromClient('apiKey','accessToken','changes','authorization','fromExternalApi'),ctx=>{constconfig=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()],},});}
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 .
Activity
daffl commentedon Mar 29, 2019
The error format is determined by the client request by setting the
Acceptheader. For JSON it should beapplication/jsonand then you should get back what you are expecting.PowerMogli commentedon Mar 29, 2019
I am sorry but that did not the trick. We still receive html.
daffl commentedon Mar 29, 2019
What is your setup? Did you configure the error handler?
PowerMogli commentedon Mar 29, 2019
daffl commentedon Mar 29, 2019
And what's the code for when you are getting the right error and when not?
PowerMogli commentedon Mar 29, 2019
This is when right error:
inside ./hooks/auth-hooks:
when not:
PowerMogli commentedon Mar 29, 2019
I am sorry that is all I can answer for. I hope it is enough to find out the issue.
KidkArolis commentedon Mar 29, 2019
Could you put a breakpoint or
console.log(req.headers)onnode_modules/@feathersjs/errors/lib/error-handler.js#97to show us what headers the request is receiving in both cases?PowerMogli commentedon Apr 1, 2019
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.
DattaramNaik commentedon Aug 29, 2023
I am using feather js backend ....
I am getting error response in html format
<title>Error</title>I want json format
I am sending application/json through client still getting html response .
daffl commentedon Aug 31, 2023
When submitted from the browser, it will always prefer HTML. You can disable HTML responses completely with the
{ html: false }option