通过LinkedIn OpenID登录后获取用户URN及资料遇403问题咨询
问题:通过LinkedIn OAuth获取用户URN以创建@用户的帖子
我需要通过LinkedIn API创建帖子并@用户,不想让用户手动输入用户名,打算通过LinkedIn OAuth完成认证。标记用户需要获取用户的URN,但目前通过OpenID只能拿到以下用户信息:
{ "sub": "782bbtaQ", "name": "John Doe", "given_name": "John", "family_name": "Doe", "picture": "https://media.licdn-ei.com/dms/image/C5F03AQHqK8v7tB1HCQ/profile-displayphoto-shrink_100_100/0/", "locale": "en-US", "email": "doe@email.com", "email_verified": true }
调用v2/me API时返回403错误,想确认是否能用登录时获取的access_token获取用户资料名称和URN,我尝试的请求代码如下:
try { const response = await axios.get("https://api.linkedin.com/v2/me", { headers: { Authorization: `Bearer ${accessToken}`, "X-Restli-Protocol-Version": "2.0.0", }, }); console.log("User Profile Data:", response.data); } catch (error) { console.error("Error fetching profile:", error.response?.data || error.message); }
授权时可用权限截图如下:
解答
可以用登录时获取的access_token获取用户URN和资料名称,核心问题是你的access_token缺少访问v2/me API所需的权限。
问题原因
OpenID默认只返回基础身份信息(如你拿到的sub、邮箱等),而v2/me API需要额外的资料访问权限。从你提供的权限截图来看,当前授权范围里没有包含访问用户资料的权限,这直接导致了403错误。
解决步骤
补充OAuth授权权限
在引导用户授权的请求中,添加r_liteprofile权限到scope参数里。比如原来的scope是openid email,修改为openid email r_liteprofile。这个权限足够获取用户的URN(即API返回的id字段)和姓名信息,完全满足标记用户的需求。重新获取access_token
让用户重新完成授权流程,确保新生成的access_token包含r_liteprofile权限。优化
v2/me请求
可以通过projection参数指定需要返回的字段,避免获取冗余数据,示例代码如下:
try { const response = await axios.get("https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)", { headers: { Authorization: `Bearer ${accessToken}`, "X-Restli-Protocol-Version": "2.0.0", }, }); console.log("用户资料(含URN):", response.data); // 这里的id就是用户的URN,格式为"urn:li:person:xxxxxx",可直接用于帖子@标记 } catch (error) { console.error("获取资料失败:", error.response?.data || error.message); }
补充说明
- 不需要申请
r_fullprofile权限,r_liteprofile已经能满足获取标记用户所需的核心信息。 - 创建帖子时,直接使用返回的
id(URN)即可实现@用户的功能,格式无需额外转换。
内容的提问来源于stack exchange,提问作者suicide11
相关产品推荐
相关产品推荐

