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

Node.js Passport LinkedIn登录失败:无法获取用户资料求助

解决LinkedIn OpenID登录获取用户信息失败问题

问题核心在于你沿用了旧API v1的逻辑,新应用启用的openid、profile、email权限对应LinkedIn的v2 API,接口端点、返回结构和旧v1完全不同,原来的linkedin.getProfile方法大概率还是调用v1接口,导致无法获取数据。

以下是具体修复步骤:

1. 更换支持v2/OpenID的Passport包

旧的passport-linkedin仅支持v1 API,需要替换为支持v2和OpenID Connect的passport-linkedin-oauth2:

npm install passport-linkedin-oauth2

2. 修改Passport策略配置与逻辑

新包的Strategy会自动处理v2 API的用户信息获取,无需手动调用getProfile方法,直接使用回调参数中的profile即可:

const LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;

passport.use(
  new LinkedInStrategy(
    {
      clientID: process.env.LINKEDIN_CLIENT_ID,
      clientSecret: process.env.LINKEDIN_CLIENT_SECRET,
      callbackURL: 'http://localhost:5000/server/api/users/linkedin/callback',
      scope: ['openid', 'profile', 'email'],
      state: true // 开启防止CSRF攻击,建议保留
    },
    async (accessToken, refreshToken, profile, done) => {
      try {
        // 适配LinkedIn v2 API的返回结构提取用户信息
        const userInfo = {
          email: profile.emails[0]?.value,
          name: profile.displayName || `${profile.name.givenName} ${profile.name.familyName}`
        };

        console.log(userInfo);
        
        let existingUser = await User.findOne({ email: userInfo.email });

        if (existingUser) {
          return done(null, existingUser);
        }

        const newUser = new User({
          name: userInfo.name,
          email: userInfo.email,
          accessToken: accessToken,
          refreshToken: refreshToken,
          type: 'linkedin'
        });

        await newUser.save();

        done(null, newUser);
      } catch (err) {
        console.log(err);
        done(err, false);
      }
    }
  )
);

3. 确认LinkedIn应用后台配置

检查开发者后台的应用设置:

  • 确保openid、profile、email权限已添加并通过审核
  • 回调URL与代码中完全一致(包括协议、端口、路径)

额外说明

如果需要手动调用API获取更多字段,要使用v2的端点https://api.linkedin.com/v2/userinfo,请求头需带上Authorization: Bearer ${accessToken}。

内容的提问来源于stack exchange,提问作者return

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:33:44