使用“Google Identity Services”手动触发打开 Google 登录弹出窗口以获取“id_token”

sp3*_*zzz 5 google-oauth

是否有一种可编程的方式可以id_token像以前一样使用“Google Identity Services” gapi.auth2.authorize?我有一个用例,我有一个完全自定义的谷歌登录按钮,通过单击它,我调用gapi.auth2.authorize以显示谷歌登录弹出窗口。用户成功登录后,我收到id_token. 然后,该令牌被发送到后端服务器以验证/验证用户身份并让他登录到我的应用程序。例如:

    const config: gapi.auth2.AuthorizeConfig = {
        client_id: <client_id>,
    scope: 'email profile openid',
    prompt: 'consent',
    response_type: 'id_token',
    include_granted_scopes: false
    };
    
    gapi.auth2.authorize(config, (response) => {
        console.log(response.id_token);
        // redirect or send to backend server
    })
Run Code Online (Sandbox Code Playgroud)

据我所知,现在有办法使用新的“Google Identity Services”API 来做到这一点。据我了解,您使用以下方法google.accounts.id进行身份验证和google.accounts.oauth2授权。使用下面的方法,google.accounts.id我可以只显示prompt(一击弹出窗口)或调用renderButton(渲染的按钮可以在某种程度上进行自定义)。并且下面的方法google.accounts.oauth2仅返回“access_token”(例如requestAccessToken)或“授权代码”(例如requestCode)。

我本以为会有一些类似requestIdToken(或requestCredential)的方法google.accounts.id

luk*_*rks 1

如何显示登录模态窗口?

据我了解,Google 不希望您创建自己的按钮并添加 onClick 侦听器来调用登录模式窗口。

相反,他们想自己渲染按钮。

google.accounts.id.renderButton([elementRef or selector], {button config})
Run Code Online (Sandbox Code Playgroud)

您可以使用他们的配置器获取该配置。

如何获取id_token?

一旦呈现按钮,您需要“初始化侦听器”(一旦它不是 onClick 事件就执行此操作)

google.accounts.id.initialize({
   client_id: [your_client_id],
   callback: (authResponse) => {
     const token = authResponse.credentials <-- I believe this is an id_token now
   }
Run Code Online (Sandbox Code Playgroud)

现在你只需点击 Google 渲染的按钮,它就会显示模式窗口。当您登录时,应该会触发包含您的 JWT 令牌的回调。