question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

how to customize http response if failed authentication?

See original GitHub issue

I have below code to use passport-jwt to verify user authentication. But it returns 500 internal error to the client if it failed authentication. How can I customize the error response with a different http status code with a different message?

router.post(
            "/user",
            passport.authenticate("admin", { session: false }),
            (req, res) => {
      ...

below is my passport setup:

const adminStrategy = new JwtStrategy(jwtOptions, (jwtPayload, next) => {
        l.info("admin payload received", jwtPayload);
        userDb.hgetall(jwtPayload.id, (err, obj) => {
            if (!err && obj) {
                if (obj.role !== "admin") {
                    next(new Error("not admin user"), false);
                } else {
                    next(null, jwtPayload);
                }
            } else {
                next(null, false);
            }
        });
    });
passport.use("admin", adminStrategy);

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:9 (1 by maintainers)

github_iconTop GitHub Comments

32reactions
tomislav13commented, Jun 17, 2019

Similar to kuldeepdhaka’s answer, maybe use it as a middleware function:

function authenticateJwt(req, res, next) {
  passport.authenticate('jwt', function(err, user, info) {
    if (err) return next(err);
    if (!user) throw new AuthError('401', 'User is not authenticated.');
    req.user = user;
    next();
  })(req, res, next);
}

router.get('/list', authenticateJwt, your_other_middleware_function1, your_other_function2, ... );
12reactions
kuldeepdhakacommented, Mar 25, 2019

Anyone looking for a quick and minimal way to take control over authentication failure responce:

// old way: no control over the authentication failure response 
router.get('/list', passport.authenticate('jwt', { session: false }),
	function(req, res, next) {
		res.send({"protected": "resource"})
	}
);

// new way: reduced to one function with json response for authentication failure

// print json response instead of string
// using Custom Callback
//http://www.passportjs.org/docs/authenticate/
function passport_authenticate_jwt(callback) {
	function hack(req, res, next) {
		passport.authenticate('jwt', function(err, user, info) {
			if (err) return next(err)
			if (!user) return res.status(401).send({
				"error": {
					"code": "INVALID_AUTHORIZATION_CODE",
					"message": "Invalid authorization code"
				}
			});

			req.user = user
			return callback(req, res, next);
		})(req, res, next);
	}

	return hack
}

router.get('/list', passport_authenticate_jwt(function(req, res, next) {
	req.send({"protected": "resource"})
}));
Read more comments on GitHub >

github_iconTop Results From Across the Web

How To Implement Custom Error Responses in Express - Auth0
Here, you will learn how to customize the 401 Unauthorized or 403 Forbidden HTTP errors by extending the Auth0 Hello World API. This...
Read more >
http - RESTful Login Failure: Return 401 or Custom Response
First off. 401 is the proper response code to send when a failed login has happened. 401 Unauthorized Similar to 403 Forbidden, ...
Read more >
Custom Unauthorized response body - Ignas Sakalauskas
A quick example to illustrate an implementation of a custom Unauthorized response body in ASP.NET Core 2.1. The implementation is based on ...
Read more >
401 Unauthorized - HTTP - MDN Web Docs
The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been completed ...
Read more >
4 Developing Custom Pages - Oracle Help Center
The custom error page is packaged as part of the custom login application. Under authentication policy, set the failure redirect URL to be...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found