使用Passport集成LinkedIn授权时Scope错误的排查求助
问题描述
使用Passport库配置LinkedIn授权,已在LinkedIn开发者控制台申请「Share on LinkedIn」和「Sign In with LinkedIn using OpenID Connect」权限,但登录时触发以下错误:
AuthorizationError: Scope "r_emailaddress" is not authorized for your application
at OAuth2Strategy.authenticate (....\node_modules\passport-oauth2\lib\strategy.js:138:25)
at attempt (....\node_modules\passport\lib\middleware\authenticate.js:369:16)
at authenticate (....\node_modules\passport\lib\middleware\authenticate.js:370:7)
at Layer.handle [as handle_request] (....\node_modules\express\lib\router\layer.js:95:5)
at next (....\node_modules\express\lib\router\route.js:149:13)
at Route.dispatch (....\node_modules\express\lib\router\route.js:119:3)
at Layer.handle [as handle_request] (....\node_modules\express\lib\router\layer.js:95:5)
at ....\node_modules\express\lib\router\index.js:284:15
at Function.process_params (....\node_modules\express\lib\router\index.js:346:12)
at next (....\node_modules\express\lib\router\index.js:280:10)
当前认证层代码:
app.get('/auth/linkedin', passport.authenticate('linkedin', { scope: ['r_emailaddress', 'r_liteprofile'], }));
补充:LinkedIn开发者控制台「Auth」标签下的OAuth 2.0 scopes:
OAuth 2.0 scopes
Scopes定义了你的应用可代表用户执行的操作。OAuth授权界面会向终端用户显示以下描述,若应用有自定义OAuth流程可能会略有不同。openid 使用你的姓名和头像
profile 使用你的姓名和头像
w_member_social 代表你创建、修改和删除帖子、评论及互动
email 使用你LinkedIn账户关联的主邮箱地址
问题原因
LinkedIn已更新OAuth 2.0的scope命名规则,代码中使用的r_emailaddress、r_liteprofile是旧版scope名称,现已被废弃,需替换为控制台中显示的新版scope。
解决方法
- 更新代码中的scope配置
将认证代码中的scope数组替换为新版名称:
app.get('/auth/linkedin', passport.authenticate('linkedin', { scope: ['openid', 'profile', 'email'], }));
openid:必须包含,对应你启用的「Sign In with LinkedIn using OpenID Connect」权限profile:替代旧的r_liteprofile,用于获取用户基本资料email:替代旧的r_emailaddress,用于获取用户邮箱
确认控制台权限
在LinkedIn开发者控制台的「Auth」标签下,确保已勾选openid、profile、email以及w_member_social(对应「Share on LinkedIn」权限),若有缺失需勾选后保存配置。重启应用
修改代码后重启Node.js应用,确保新的scope配置生效。
内容的提问来源于stack exchange,提问作者Mandroid

