簡體   English   中英

在 Vue.js 應用程序上使用 Google (GIS) 登錄

[英]Sign In With Google (GIS) on Vue.js Application

顯然谷歌正在停止為gapi.oauth2提供服務。 我正在嘗試使用他們新的“使用 Google 登錄”工具,但它們非常令人困惑。

項目結構
我有一個 Vue 前端,我需要允許用戶使用谷歌登錄。 然后我需要使用 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')"

因此,當我在App.vue但不在AccessRequest.vue中時,似乎window.google存在。 我對所有這些應該如何工作有什么大的誤解嗎?

此“使用 Google 按鈕登錄”是否適用於 OIDC 服務器流程?

這是我的代碼
首先,您必須將此代碼 index.html 放在公共文件夾中

<script src="https://accounts.google.com/gsi/client" async defer></script>
<template>
 <div ref="googleLoginBtn" />
</template>
<script>
  export default(){
    mounted() {
      const gClinetId = [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: 'Login',
          size: 'large',
          width: '366', // max width 400
          theme: 'outline' // option : filled_black | outline | filled_blue
        }
      )
    },
    methods: {
      async handleCredentialResponse(response) {
         console.log(response.credential)
         // Put your backend code in here
      }
    }
  }
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM