Google One Tap 登录后如何获取 OAuth 令牌:一键登录 Google oAuth 的 JWT 令牌响应

Aka*_*nan 5 javascript oauth google-signin google-one-tap

我一直在阅读文档,到目前为止还没有成功,还需要 OAuth 访问令牌。但是,Google Identity 服务不会返还 oAuth 访问令牌。相反,它返回一个 JWT 令牌。

我正在寻找使用一键登录的 JWT 令牌响应进行传递的方法,以便我可以取回 oAuth 访问令牌。

文档链接: Google 一键登录

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

    window.onload = function () {
        google.accounts.id.initialize({
            client_id: 'myid.apps.googleusercontent.com',
            callback: handleCredentialResponse
        });
        google.accounts.id.prompt();
    }

</script>

<script>
    function parseJwt(token) {
        var base64Url = token.split('.')[1];
        var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        var jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));

        return JSON.parse(jsonPayload);
    };

    function handleCredentialResponse(response) {
        console.log(response);
        const responsePayload = parseJwt(response.credential);
        console.log(responsePayload);
    }
</script>
Run Code Online (Sandbox Code Playgroud)

Aka*_*nan 10

@user872176 这就是我解决问题的方法

我们可以使用身份服务来登录用户,并使用用户电子邮件作为 oAUth 流程的提示。

在我之前的评论中,我创建了一个表单并请求访问令牌,但我们可以使用谷歌身份服务向用户询问应用程序的 oAuth。通过一键登录提示。

打开一键登录提示

function oneTapSignInPrompt() {
  google.accounts.id.initialize({
    client_id: '#',
    callback: handleCredentialResponse,
    cancel_on_tap_outside: false,
    itp_support: true,
  });
  google.accounts.id.prompt();
}
Run Code Online (Sandbox Code Playgroud)

处理一键响应

function handleCredentialResponse(response) {
  // One Tap Sign in returns a JWT token.
  const responsePayload = parseJwt(response.credential);
  if (!responsePayload.email_verified) {
    showInvalidEmailToast();
    oneTapSignInPrompt();
  } else {
    // We are passing the signed in email id to oAuth.
    // If we pass an email id to oAuth consent.
    // If the user has already given the oAuth consent. it will get auto selected.
    oauthSignIn(responsePayload.email);
  }
}
Run Code Online (Sandbox Code Playgroud)

解析 JWT

function parseJwt(token) {
  var base64Url = token.split('.')[1];
  var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  var jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));
  return JSON.parse(jsonPayload);
};
Run Code Online (Sandbox Code Playgroud)

oAuth 同意

    // This method request the oauth consent for the passed in google account.
function oauthSignIn(googleId) {
  const client = google.accounts.oauth2.initTokenClient({
    client_id: '',
    scope: 'https://www.googleapis.com/auth/userinfo.profile',
    hint: googleId,
    prompt: '',// Specified as an empty string to auto select the account which we have already consented for use.
    callback: (tokenResponse) => {
    access_token = tokenResponse.access_token;
    onOneTapSignIn(access_token); // Reuse the token whichever way you want
    },
  });
  client.requestAccessToken();
}
Run Code Online (Sandbox Code Playgroud)