Passport LinkedIn登录:用户取消授权触发500错误而非跳转failureUrl
It sounds like you're hitting a common gotcha with the passport-linkedin strategy: when a user cancels the authorization flow, Passport is throwing an unhandled error instead of redirecting to your failureRedirect URL. Here's why that happens and how to fix it:
The Root Cause
By default, the passport.authenticate() middleware will call next(err) when it encounters an error (like the "user canceled authorization" response from LinkedIn), which triggers Express's default error handler and results in a 500 status. The failureRedirect only kicks in when there's no error but authentication fails (e.g., invalid credentials), not when an explicit error is thrown during the flow.
Solution: Use a Custom Callback
Instead of relying on the built-in failureRedirect, use Passport's custom callback pattern to handle errors and authentication outcomes manually. This gives you full control over redirects when the user cancels:
app.get('/auth/linkedin/callback', (req, res, next) => { passport.authenticate('linkedin', (err, user, info) => { // Handle any errors (including user canceling authorization) if (err) { console.error('LinkedIn auth error:', err); return res.redirect('/login'); // Redirect to your failure URL } // If no user was returned, authentication failed if (!user) { return res.redirect('/login'); } // Log the user in if authentication succeeded req.logIn(user, (loginErr) => { if (loginErr) { return next(loginErr); } // Redirect to your success page return res.redirect('/dashboard'); }); })(req, res, next); });
Additional Checks
- Update
passport-linkedin: Make sure you're using the latest version of the strategy, as older versions might have bugs handling cancel responses. Runnpm update passport-linkedin-oauth2(or the correct package name for your strategy) to upgrade. - Verify LinkedIn App Settings: Double-check that your callback URL in the LinkedIn Developer Portal matches exactly what's configured in your Express app—mismatched URLs can also trigger unexpected errors.
- Log Errors: Add
console.errorstatements (like in the example) to see the exact error message from LinkedIn, which can help debug if there are other issues at play.
This approach ensures that both errors (like user cancellation) and authentication failures will redirect to your /login page instead of throwing a 500 error.
内容的提问来源于stack exchange,提问作者Randhir Singh

