我使用以下代码让用户能够通过Javascript API使用他们的Google帐户登录。
HTML
<a id="gp_login" href="javascript:void(0)" onclick="javascript:googleAuth()">Login using Google</a>
使用Javascript
function gPOnLoad(){
// G+ api loaded
document.getElementById('gp_login').style.display = 'block';
}
function googleAuth() {
gapi.auth.signIn({
callback: gPSignInCallback,
clientid: googleKey,
cookiepolicy: "single_host_origin",
requestvisibleactions: "http://schema.org/AddAction",
scope: "https://www.googleapis.com/auth/plus.login email"
})
}
function gPSignInCallback(e) {
if (e["status"]["signed_in"]) {
gapi.client.load("plus", "v1", function() {
if (e["access_token"]) {
getProfile()
} else if (e["error"]) {
console.log("There was an error: " + e["error"])
}
})
} else {
console.log("Sign-in state: " + e["error"])
}
}
function getProfile() {
var e = gapi.client.plus.people.get({
userId: "me"
});
e.execute(function(e) {
if (e.error) {
console.log(e.message);
return
} else if (e.id) {
// save profile data
}
})
}(function() {
var e = document.createElement("script");
e.type = "text/javascript";
e.async = true;
e.src = "https://apis.google.com/js/client:platform.js?onload=gPOnLoad";
var t = document.getElementsByTagName("script")[0];
t.parentNode.insertBefore(e, t)
})()
这段代码工作正常。我想使用上面的代码(使用Javascript)从他们的Google帐户登录用户,而不会触发弹出窗口。例如,用户单击登录链接,在同一窗口/选项卡中询问应用程序权限,用户授予权限,用户重定向回Google登录链接所在的页面,保存配置文件数据并登录用户。
Google API不提供此类功能。你应该坚持使用gapi.auth.signIn。我知道只有一种方法可以使它工作,但它非常hacky。
gapi.auth.signIn打开身份验证窗口。在app1中保存身份验证窗口网址。而不是调用gapi.auth.signIn,将用户重定向到该URL。
要将成功的身份验证重定向回您的网站,请在url2中添加/修改redirect_url param。请记住,redirect_uri必须在开发人员控制台中注册。
示例:https://accounts.google.com/o/oauth2/auth?client_id=1234567890.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.login&immediate=false&response_type=token&redirect_uri = http://example.com
这样谷歌会将用户重定向回您的网站。 access_token是通过GET参数提供的。
1如果谷歌改变他们的API,这可能会破坏(因为这种方法绕过了JS API,并假设所有那些URL中的参数永远都会得到支持)。
2Redirect_url在offline access flow documentation中引入。我认为这个参数不适用于任何其他情况。
我强烈建议不要使用这个想法(因为它绕过JS API并使用未记录的功能)。坚持使用gapi.auth.signIn。
如果要重定向到其他页面,可以使用ux_mode参数(选项为'redirect'或'popup')并设置redirect_uri。
您还需要在Google项目页面上授权OAuth客户端的URL。
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES,
ux_mode: 'redirect',
//redirect_uri: custom url to redirect'
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}