use*_*ser 4 javascript local-storage google-chrome-extension firefox-addon-webextensions
我有一个书签的Firefox /铬WebExtension(使用标准popup,content和background脚本).我的api服务器有一个返回JSON Web令牌的/ login路由,Web应用程序将其存储在本地存储中.我可以完全控制扩展,api和Web应用程序.
赤脚的方法是让用户通过弹出窗口登录,并将background.js中的身份验证令牌保存到WebExtension的本地存储中.但我真的只想让用户在我的网站上进行身份验证,并将相同的身份验证同样适用于该扩展程序.
有没有办法分享身份验证令牌?我看到Pocket和很多其他人这样做,但我不确定如何.
您可以将令牌存储为cookie.Cookie的工作原理localStorage与此类似,但额外的是,默认情况下,它们也包含在每个到服务器的HTTP请求中.这就是诀窍.Chrome扩展程序可以使用webRequestAPI 获取对HTTP请求的访问权限.因此,它可以查看请求标头并了解您的cookie.将该Web令牌作为cookie使其可用于扩展.
但是你还需要等待用户打开你的网站,让HTTP请求流动并准备好被窥视,对吧?并不是的.您可以直接从扩展程序发出ajax请求.
这是为了说明整个事情是如何工作的:
表现:
"permissions": [
"webRequest",
"webRequestBlocking",
"*://*.my_site.com/*"
]
Run Code Online (Sandbox Code Playgroud)
背景页面:
function callback (details) {
//
token = func_extract_token_from_headers(details.requestHeaders);
chrome.webRequest.onBeforeSendHeaders.removeListener(callback);
return {cancel: false} // set to true to prevent the request
// from reaching the server
}
chrome.webRequest.onBeforeSendHeaders.addListener (callback,
{urls: ["http://www.my_site.com/*", "https://www.my_site.com/*"]},
["blocking", "requestHeaders"]);
var xurl = "https://www.my_site.com/";
var xhr = new XMLHttpRequest();
xhr.open("GET", xurl, true);
xhr.send();
Run Code Online (Sandbox Code Playgroud)
我应该提一下,有一种更清洁的方法,但由于CSP - Content Secutiry Policiy,它目前无效.正如wOxxOm在评论中所提到的,在后台页面内的iframe中打开网站应该可行,并添加了网站的CSP白名单.这种方法还可以避免提示用户提供凭据,并且更清洁.不幸的是,目前还没有工作
编辑:
抱歉,我最后一次声明错了:打开外部页面的iframe会在后台页面中被屏蔽.要在后台页面(或弹出窗口)中显示它,只需将CSP列入白名单 - 如下所示.
除了在iframe中打开页面的业务外,您还需要与之通信.这应该使用window.postMessage API完成
这是为了说明这一切应该如何结合在一起:
表现:
// Whitelist your website
"content_security_policy": "script-src 'self' https://my_site.com/; object-src 'self'"
// Have the background declared as html
"background": { "page": "background.html"}
Run Code Online (Sandbox Code Playgroud)
背景:
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if(event.origin == "https://my_site.com"); // you may want to check the
// origin to be your site
chrome.storage.storage.local.set({'auth_token': event.data}); // the token
}
iframe = document.createElement('iframe');
iframe.src = "https://my_site.com/";
// Have a div ready to place iframe in
document.getElementById('div').appendChild(iframe);
iframe.contentWindow.postMessage("give_token", "https://my_site.com")
Run Code Online (Sandbox Code Playgroud)
网页:
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if(event.origin == "your_extension_id_aeiou12345");
event.source.postMessage(''+localStorage.auth_token, event.origin);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
此外,要使网站显示在iframe中,请确保X-frame-options响应标头未设置为阻止值.您可以将其删除,或将其设置为非阻止值,或者将扩展名的网址列入白名单.