显然谷歌正在停止为
gapi.oauth2
提供服务。我正在尝试使用他们的新“使用 Google 登录”工具,但它们非常令人困惑。
项目结构
我有一个 Vue 前端,我需要允许用户使用 google 登录。然后我需要使用 OIDC 服务器流在我的后端对它们进行身份验证。
我的文件结构是 Vue CLI 为您提供的默认结构。
我遵循了这些文档,但它们没有解释如何真正为用户提供登录的机会。比如我们如何启动整个流程?我想这个流程可能是由新的“使用 Google 按钮登录”启动的,但我不知道如何让这个按钮工作。 这是我现在正在尝试的方法:
在
App.vue
我有以下内容
created() {
loadGSIClient().then((this.GSILoaded = true));
}
googleAuth.js
export function loadGSIClient() {
console.log("loading GSI");
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = "https://accounts.google.com/gsi/client";
script.onload = () => {
var client = window.google.accounts.oauth2.initCodeClient({
client_id: process.env.VUE_APP_CLIENT_ID,
scope: "https://www.googleapis.com/auth/calendar.readonly",
ux_mode: "redirect",
redirect_uri:
"http://localhost:5001/sig-wig/us-central1/handleRedirect",
});
resolve(client);
};
script.onerror = (message, url, line, column, error) => {
reject({ message, url, line, column, error });
};
});
}
然后,在我的登录文件中
AccessRequest
我有
created() {
var google = window.google;
google.accounts.id.initialize({
client_id: process.env.VUE_APP_CLIENT_ID,
callback: () => {
"I'm a callback";
},
});
google.accounts.id.renderButton(
document.getElementById("buttonDiv"),
{ theme: "outline", size: "large" } // customization attributes
);
},
但是该设置总是会引发错误
Error in created hook: "TypeError: Cannot read properties of undefined (reading 'accounts')"
所以当我在 window.google
时,似乎
App.vue
存在,但在 AccessRequest.vue
中不存在。我对这一切应该如何运作有什么重大误解吗?“使用 Google 按钮登录”是否适用于 OIDC 服务器流程?
<script src="https://accounts.google.com/gsi/client" async defer></script>
<template>
<div ref="googleLoginBtn" />
</template>
<script>
export default(){
mounted() {
const gClientId = [Your Client Id]
window.google.accounts.id.initialize({
client_id: gClientId,
callback: this.handleCredentialResponse,
auto_select: true
})
window.google.accounts.id.renderButton(
this.$refs.googleLoginBtn, {
text: 'signin_with', // or 'signup_with' | 'continue_with' | 'signin'
size: 'large', // or 'small' | 'medium'
width: '366', // max width 400
theme: 'outline', // or 'filled_black' | 'filled_blue'
logo_alignment: 'left' // or 'center'
}
)
},
methods: {
async handleCredentialResponse(response) {
console.log(response.credential)
// Put your backend code in here
}
}
}
</script>
内
index.html
附加于
<body>
<!-- Google Oauth -->
<div id="g_id_onload"
data-client_id="YOUR_CLIENT_ID"
data-callback="handleCredentialResponse">
</div>
<script src="https://accounts.google.com/gsi/client"></script>
<script>
function handleCredentialResponse(respones){
console.log(respones)
}
</script>