johnbrett / hapi-auth-bearer-token

Simple Bearer authentication scheme plugin for hapi, accepts token by Header, Cookie or Query parameter.
MIT License
218 stars 46 forks source link

How to customize own error? #188

Closed itsgratien closed 5 years ago

itsgratien commented 5 years ago

Hello, I have used hapi-auth-bearer-token, it is working, but I want to ask something, is it possible to generate our own error message once authentication failed? instead of returning messages like this { "statusCode": 401, "error": "Unauthorized", "message": "Bad token", "attributes": { "error": "Bad token" } if it is possible how? thanks.

johnbrett commented 5 years ago

Can you give me an example of what you'd like your error to look like?

johnbrett commented 5 years ago

likely you're looking for something that hapi itself would handle though, not this library: https://hapijs.com/api#error-transformation

johnbrett commented 5 years ago

Ok going to close as I think the above link answers the question, feel free to continue the conversation if you have more questions though.

itsgratien commented 5 years ago

@johnbrett error message would look like this { "statusCode": 401, "error": "Unauthorized", "message": "sorry you must be authenticated" }

itsgratien commented 5 years ago

Can you give me an example of what you'd like your error to look like?

{ "statusCode": 401, "error": "Unauthorized", "message": "sorry you must be authenticated" }

itsgratien commented 5 years ago

I had another question, after registering AuthBear Token and use it, how should I access information of the authenticated user in other routes. here is my code `await server.register(AuthBearer); //register authbear strategy server.auth.strategy('simple', 'bearer-access-token', { validate: async(req, token , h) => { //decode token const decode = jwt.verify(token, secretOrKey); const check = await User.findOne({username: decode.username}); const isValid = check ? true : false ; const credentials = { token }; return { isValid, credentials}; }); server.auth.default('simple');

// here the user must perform this action once he/she is authenticated. server.route({ method: 'POST', path: '/signup', handler: signUp }); ` is it possible to access user id, or username in routes to store id of user who created something. i would like to know how can i do it.

johnbrett commented 5 years ago

have you read the hapi docs? This is all in the request object: https://hapijs.com/api#request.auth

I'd read the entire hapijs API docs before doing anything else, it doesn't take that long and will likely answer any further questions you have

itsgratien commented 5 years ago

I am reading it, hopefully, I will solve this problem. thank you.