使用 google 登入網站

之前一篇有提到如何用 google 登入網站,不過當時那篇找到的範例可能太舊了有點問題,今天要再使用的時候又找了比較新的方法,前面跟上一篇一樣要先在 google 那邊開一個新的憑證,接下來改這樣做:

接著讀入這段


在 meta 加上這段


放一顆按鈕登入

使用 google 登入和取得登入資訊的程式
function onSignIn(googleUser) {
  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
}

要登出的話則是加上一顆按鈕並綁上以下的程式就可以了
function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
    });
  }

這邊要注意的是如果登入和登出沒有寫在同一頁,我們要執行登出的話需要先初始化像這樣


function onLoad() {
      gapi.load('auth2', function() {
        gapi.auth2.init();
      });
    }


一樣可以把取得的登入資訊在寫到自己的系統內做進一步的應用。

參考: Integrating Google Sign-In into your web app

留言