Google 身份 - 单击自定义按钮即可触发登录过程

Pra*_*bhu 12 google-signin google-identity

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

<div class="cust1" onclick="triggerGoogleSignIn">Sign in with Google</div>
Run Code Online (Sandbox Code Playgroud)

现在我希望仅在单击此按钮时登录。我检查了文档并尝试了g_id_signinrenderButton 类方法。

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

triggerGoogleSignIn(){
  ????
}
Run Code Online (Sandbox Code Playgroud)

我应该调用什么方法?

W.S*_*.S. 5

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

加载库后,

<script src="https://accounts.google.com/gsi/client" async defer></script>
Run Code Online (Sandbox Code Playgroud)

您可以通过调用以下命令来初始化客户端:

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
});
Run Code Online (Sandbox Code Playgroud)

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

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

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


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

如果您想渲染自己的按钮并通过 JavaScript 触发身份验证流程,请使用以下步骤

将客户端库包含在您的 head 标签中

<script src="https://accounts.google.com/gsi/client" async defer></script>
Run Code Online (Sandbox Code Playgroud)

加载库后,您可以使用 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
  });
}
Run Code Online (Sandbox Code Playgroud)

要登录,只需调用提示即可。

google.accounts.id.prompt();
Run Code Online (Sandbox Code Playgroud)

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