2012-09-12

使用Google帳號登入自己的網站

1.申請一個google帳號

2.登入 APIs Console

3.點選建立專案(Create project)



4.點選 Create an OAuth 2.0 client ID


5.建立你的產品

全部設定完後再按 Next

6.設定完成後會出現的畫面

7.讓使用者連結到google登入授權頁面


參考格式範例 (來源)

https://accounts.google.com/o/oauth2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&
state=%2Fprofile&
redirect_uri=https%3A%2F%2Foauth2-login-demo.appspot.com%2Foauthcallback&
response_type=token&
client_id=812741506391.apps.googleusercontent.com

參數說明(來源)

scope : 你需要使用者同意授權給你的權限(可用「+」來連結多個權限)
scope可用參數 (只是看起來像網址)
  • 帳號基本資訊: https://www.googleapis.com/auth/userinfo.profile
  • 使用者email: https://www.googleapis.com/auth/userinfo.email


client_id :第6步驟圖內的 Client ID

redirect_uri : 第6步驟圖內的 Redirect URIs,使用者登入成功或失敗會連結到的地方

 8.連結後的結果

 當使用者完成在google的授權動作之後,會連結到你所設定Redirect URIs頁面,
 此時使用者在此頁面的網址會多幾個參數

 如果登入成功時

RedirectURIs網址#access_token=存取代碼&token_type=Bearer&expires_in=3600

 如果登入失敗(使用者拒絕授權)

 RedirectURIs網址#error=access_denied

 如何取得網址上的參數

 可以使用javascrip的方式(參考)

// First, parse the query string 首先解析網址參數
var params = {}, queryString = location.hash.substring(1),
    regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(queryString)) {
  params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}

// And send the token over to the server 送出使用者資訊請求給Google
var req = new XMLHttpRequest();
// consider using POST so query isn't logged
req.open('GET', 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + params['access_token'], true);

req.onreadystatechange = function (e) {
  if (req.readyState == 4) {
     if(req.status == 200){
       回傳資訊 = JSON.parse(req.responseText);
   }
  else if(req.status == 400) {
        alert('There was an error processing the token.')
    }
    else {
      alert('something else other than 200 was returned')
    }
  }
};
req.send(null);

 參考資料

 Using OAuth 2.0 for Login

沒有留言:

張貼留言