好的,解决了她。这个网站基本上是这样描述的:
http://smus.com/oauth2-chrome-extensions/
但并非所有内容都在此处进行了解释。所以:
首先,您需要一个 API 客户端 ID 和客户端密码,以便用户授权您使用他们的详细信息。以下步骤将以适用于 chrome 扩展的方式进行设置:
- Google API 控制台
- 创建 API
- 转到 API 访问
- 创建客户端 ID
- 给它一个名称和一个徽标,当用户被要求允许您的应用程序检索他们的详细信息时,将显示此名称和徽标。下一个
- 选择网络应用程序
- 点击更多获取URI和授权的javascript来源
- 将重定向 URI 设置为 http://www.google.com/robots.txt
- 删除 javascript origins 字段以便没有
- 单击“确定”或其他任何内容,复制客户端 ID 和客户端密码以供以后使用。
其次,您需要 oauth2 javascript 库,该库可在此处获得:
https://github.com/borismus/oauth2-extensions/tree/master/lib
您需要将它放在一个名为 oauth2 的文件夹中,该文件夹与您的 html 文件位于同一目录中。
在你的 html 文件中添加以下内容:
<script type="text/javascript" src="oauth2/oauth2.js"></script>
<script type="text/javascript">
var googleAuth = new OAuth2('google', {
client_id: ' $(YOUR CLIENT ID HERE) ',
client_secret: ' $(YOUR CLIENT SECRET HERE) ',
api_scope: 'https://www.googleapis.com/auth/userinfo.email'
});
googleAuth.authorize(function() {
// We should now have googleAuth.getAccessToken() returning a valid token value for us
// Create an XMLHttpRequest to get the email address
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if( xhr.readyState == 4 ) {
if( xhr.status == 200 ) {
var parseResult = JSON.parse(xhr.responseText);
// The email address is located naw:
var email = parseResult["email"];
}
}
}
// Open it up as GET, POST didn't work for me for the userinfo
xhr.open("GET","https://www.googleapis.com/oauth2/v1/userinfo",true);
// Set the content & autherization
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', "OAuth " + googleAuth.getAccessToken() );
xhr.send(null);
// Debugging stuff so we can see everything in the xhr. Do not leave this in production code
console.log(xhr);
});</script>
在你的 manifest.json 中你需要:
“权限”:[“https://accounts.google.com/o/oauth2/token”、“https://www.googleapis.com/oauth2/v1/userinfo”]
您还需要在清单文件中:
"content_scripts": [ {
"matches": ["http://www.google.com/robots.txt*"],
"js": ["oauth2/oauth2_inject.js"],
"run_at": "document_start" }
这应该很照顾它。