谷歌身份-点击自定义按钮即可触发登录过程



我正在尝试将新的Google Identity API集成到我的项目中。我有一个自定义按钮,比如说div.

<div class="cust1" onclick="triggerGoogleSignIn">Sign in with Google</div>

现在我只想点击这个按钮登录。我查看了文档并尝试了g_id_signin类renderButton方法。

但这些方法正在取代我的自定义按钮外观。

triggerGoogleSignIn(){
????
}

我应该调用什么方法?

为了在Google API调用期间获得用于授权的访问令牌,您首先使用以下步骤通过OAuth2.0流进行身份验证:

加载库后,

<script src="https://accounts.google.com/gsi/client" async defer></script>

通过调用初始化客户端

const tokenClient = google.accounts.oauth2.initTokenClient({
client_id: "YOUR_GOOGLE_CLIENT_ID",
scope: "THE_REQUESTED_SCOPES",
prompt: "SELECT_A_PROMPT_OPTION", // '' | 'none' | 'consent' | 'select_account'
callback: handleCredentialResponse // your function to handle the response after login. 'access_token' will be returned as property on the response
});

要请求新的访问令牌,请调用requestAccessToken

const overrideConfig = {
prompt: "SELECT_A_PROMPT_OPTION", // '' | 'none' | 'consent' | 'select_account'
}
tokenClient.requestAccessToken(overrideConfig) // open the prompt, overrideConfig is optional

类型可以在此处找到,并通过执行npm install --save-dev @types/google.accounts进行安装


如果您需要id_token进行身份验证才能登录到自己的应用程序,则可以选择Sign In With Google按钮。

如果您想呈现自己的按钮并通过javascript触发身份验证流,请使用以下步骤:

在你的头标签中包括客户端库

<script src="https://accounts.google.com/gsi/client" async defer></script>

加载库后,使用client_id进行初始化,并设置一个回调来处理登录后的响应

function handleCredentialResponse(response) {
var id_token = response.credential // validate and decode the JWT credential, using a JWT-decoding library
}
window.onload = function () {
google.accounts.id.initialize({
client_id: "YOUR_GOOGLE_CLIENT_ID",
callback: handleCredentialResponse
});
}

要登录,只需按提示即可。

google.accounts.id.prompt();

类型可以在此处找到,并通过执行npm install --save-dev @types/google-one-tap进行安装

当'的jshttps://accounts.google.com/gsi/client'加载成功第一步,你可以设置一个客户端来获得的结果

client = window.google.accounts.oauth2.initTokenClient({
client_id: clientId,
scope: 'https://www.googleapis.com/auth/contacts.readonly',
callback: tokenResponse => handleCredentialResponse(tokenResponse),
})

第二步,当你点击自定义的按钮时

client.requestAccessToken()

最后,您可以在handleCredentialResponse 的函数中获得结果

根据文档:

为了支持身份验证和授权时刻的明确分离,不再支持用户同时登录到您的应用程序和他们的谷歌帐户,同时发布访问令牌。

使用谷歌身份服务,您只能通过谷歌登录在浏览器内获得JWT代币

最新更新