You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Passport LinkedIn登录:用户取消授权触发500错误而非跳转failureUrl

Fixing 500 Error When User Cancels LinkedIn Authorization with Passport

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. Run npm 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.error statements (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:46:57