通过Chrome扩展实现身份验证(仿Grammarly登录流程)
实现Chrome扩展与网站登录门户的同步验证(仿Grammarly流程)
你猜的没错,Grammarly这类工具就是靠浏览器Cookie跨域共享+Chrome扩展读取验证实现的:用户在官网登录后,网站把登录凭证存在Cookie里,扩展通过Chrome的API读取这个Cookie,再调用后端接口验证凭证有效性,从而同步登录状态。下面是可运行的实现方案和细节指导:
一、网站端设置符合要求的登录Cookie
用户登录成功后,后端需要设置一个扩展能读取到的Cookie,关键属性必须配置正确:
- 域名设为主域名(比如
.yourdomain.com),确保官网和扩展都能访问; - 若打算用扩展JS直接读取,不要开启
HttpOnly;若用Chrome官方的chrome.cookiesAPI,开启HttpOnly更安全(能防XSS攻击); - HTTPS环境下必须开启
Secure,SameSite根据跨域需求设为Lax或None(跨域场景用None)。
后端示例(Node.js):
// 登录接口成功后设置Cookie res.cookie('user_auth_token', 'your_jwt_token_here', { domain: '.yourdomain.com', // 主域名,覆盖官网和扩展关联域名 maxAge: 30 * 24 * 60 * 60 * 1000, // 30天有效期 httpOnly: false, // 若用chrome.cookies API可设为true secure: true, // HTTPS环境强制开启 sameSite: 'Lax' // 普通场景用Lax,跨域登录用None });
二、配置Chrome扩展的权限
在manifest.json里必须声明相关权限,否则扩展无权读取网站Cookie:
{ "manifest_version": 3, "name": "同步登录扩展", "version": "1.0", "permissions": [ "cookies", "storage" ], "host_permissions": [ "https://*.yourdomain.com/*" // 匹配官网域名,允许读取该域名下的Cookie ], "action": { "default_popup": "popup.html" }, "background": { "service_worker": "background.js" } }
三、扩展端实现Cookie读取与状态同步
有两种靠谱的实现方式,按需选择:
方式1:用Chrome Cookies API(推荐,支持HttpOnly Cookie)
这种方式安全性更高,可读取带HttpOnly标记的Cookie。可以在后台服务worker里监听Cookie变化,自动同步登录状态,也能在弹窗里主动拉取状态:
background.js(后台服务worker):
// 监听Cookie变化,自动同步登录状态 chrome.cookies.onChanged.addListener((changeInfo) => { if (changeInfo.cookie.name === 'user_auth_token' && changeInfo.cookie.domain.includes('yourdomain.com')) { if (changeInfo.removed) { // 用户登出,清空扩展存储的登录信息 chrome.storage.local.set({ isLoggedIn: false, userInfo: null }); } else { // 调用后端接口验证token并获取用户信息 fetch('https://api.yourdomain.com/verify-token', { headers: { 'Authorization': `Bearer ${changeInfo.cookie.value}` } }) .then(res => res.json()) .then(userInfo => { chrome.storage.local.set({ isLoggedIn: true, userInfo }); // 通知弹窗更新UI chrome.runtime.sendMessage({ type: 'LOGIN_SUCCESS', userInfo }); }) .catch(err => { console.error('Token验证失败:', err); chrome.storage.local.set({ isLoggedIn: false }); }); } } });
popup.js(弹窗逻辑):
document.addEventListener('DOMContentLoaded', () => { // 打开弹窗时获取当前登录状态 chrome.storage.local.get(['isLoggedIn', 'userInfo'], (result) => { const loginBtn = document.getElementById('loginBtn'); const userInfoEl = document.getElementById('userInfo'); if (result.isLoggedIn) { loginBtn.style.display = 'none'; userInfoEl.textContent = `欢迎,${result.userInfo.username}`; } else { loginBtn.addEventListener('click', () => { // 打开官网登录页面 chrome.tabs.create({ url: 'https://yourdomain.com/login' }); }); } }); // 监听后台发来的登录成功消息 chrome.runtime.onMessage.addListener((message) => { if (message.type === 'LOGIN_SUCCESS') { document.getElementById('loginBtn').style.display = 'none'; document.getElementById('userInfo').textContent = `欢迎,${message.userInfo.username}`; } }); });
方式2:用内容脚本读取(仅适用于非HttpOnly Cookie)
如果网站Cookie未开启HttpOnly,可以用内容脚本注入到官网页面,直接读取Cookie后传给扩展后台:
content.js(注入到官网的内容脚本):
// 读取登录Cookie并传给后台 const authToken = document.cookie.split('; ').find(row => row.startsWith('user_auth_token='))?.split('=')[1]; if (authToken) { chrome.runtime.sendMessage({ type: 'SET_AUTH_TOKEN', token: authToken }); }
background.js(接收并验证Token):
chrome.runtime.onMessage.addListener((message) => { if (message.type === 'SET_AUTH_TOKEN') { fetch('https://api.yourdomain.com/verify-token', { headers: { 'Authorization': `Bearer ${message.token}` } }) .then(res => res.json()) .then(userInfo => { chrome.storage.local.set({ isLoggedIn: true, userInfo }); }) .catch(() => { chrome.storage.local.set({ isLoggedIn: false }); }); } });
四、登出同步
官网登出时,后端删除对应的user_auth_tokenCookie,扩展的onChanged监听器会自动捕获到变化,然后清空扩展存储的登录状态即可。
关键注意事项
- 必须使用HTTPS:Chrome对Cookie的安全限制严格,HTTP环境下
Secure属性无效,跨域Cookie会被拦截; - 权限配置要准确:
host_permissions必须包含官网域名,否则扩展无法读取Cookie; - 优先用Manifest V3:Chrome目前主推V3版本,V2即将被淘汰;
- 用JWT作为凭证:把登录凭证做成JWT,后端验证时直接解密即可,无需查询数据库,效率更高。
内容的提问来源于stack exchange,提问作者imLightSpeed
相关产品推荐
相关产品推荐

