如何在Chrome Extension v3中利用authToken获取谷歌账户详细信息?
在Chrome扩展Manifest V3中使用Auth Token获取更多用户信息
你已经通过chrome.identity.getAuthToken拿到了授权Token,要获取头像、用户名这类更多信息,需要调用Google People API,步骤如下:
1. 更新扩展Manifest配置
在manifest.json中补充OAuth2的权限范围和配置,确保拥有获取用户基本资料的权限:
{ "manifest_version": 3, "name": "你的扩展名称", "permissions": ["identity"], "oauth2": { "client_id": "你的Google OAuth客户端ID.apps.googleusercontent.com", "scopes": [ "https://www.googleapis.com/auth/userinfo.profile" ] } }
2. 调用Google People API获取信息
用拿到的Auth Token作为请求头,调用API获取指定字段的用户信息:
chrome.identity.getAuthToken({interactive: true}, function(token) { if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError); return; } // 请求用户名称和头像,可根据需求调整personFields参数 fetch('https://people.googleapis.com/v1/people/me?personFields=names,photos', { headers: { 'Authorization': `Bearer ${token}` } }) .then(res => res.json()) .then(userData => { // 提取所需信息 const userName = userData.names[0]?.displayName; const avatarUrl = userData.photos[0]?.url; console.log('用户名:', userName); console.log('头像地址:', avatarUrl); // 若需要更多信息,可修改personFields参数,比如添加nicknames、birthdays等 }) .catch(err => console.error('获取用户信息失败:', err)); });
3. 关键说明
- personFields参数:必须明确指定要获取的字段,API不会返回所有默认字段。比如
names,photos,emailAddresses可以同时获取名称、头像和邮箱,具体可按需添加字段。 - API启用:确保你的Google Cloud项目中已经启用了People API,否则会返回权限错误。
- 客户端ID配置:OAuth客户端ID需要和你的扩展ID匹配,可在Chrome扩展管理页面查看当前扩展的ID,同步到Google Cloud的OAuth配置中。
内容的提问来源于stack exchange,提问作者chengfengwang
相关产品推荐
相关产品推荐

