顯示具有 oauth 標籤的文章。 顯示所有文章
顯示具有 oauth 標籤的文章。 顯示所有文章

2022年5月22日 星期日

Go 開發筆記 - 使用 golang.org/x/oauth2 與 Facebook 登入 / Google OAuth 串接

最近評估網站是否從 PHP 翻到 Golang ,研究了一下關於串接 OAuth2 相關部分。早年在串 FB 登入時,都是直接使用 Facebook PHP SDK ,雖然都知道底層還是 OAuth2 ,但不免還是擔心要串時很麻煩(主要是很懶再刻一份)。稍微研究了一下,原來有 golang.org/x/oauth2 套件可以用,裡頭有支援了各式各家的登入機制,非常方便。

接著反而開始複習起來 Facebook 登入 該怎樣處理,過程:
  • 建立一個 FB 應用程式 developers.facebook.com/apps/
  • 設定 FB 登入相關事宜,包括應用程式網域(添加 localhost)、FB 登入用戶端 OAuth 設定,如 有效的 OAuth 重新導向 URI
  • 處理相關雜事
結果處理相關雜事反而耗掉最多時間,包括:
  • FB應用程式要儲存時,還得弄個 隱私政策網址 跟 用戶資料刪除 網頁
  • FB登入相關,要求都走 https 溝通,變成要研究 golang gin 如何跑 https web server 出來、憑證該怎樣產生等
  • 寫完程式後,體驗流程後,想弄個 github 筆記一下且降低程式碼變動,開始規劃如何靠 YAML 檔案來抽換設定檔
大概就是如此,花了不少時間。最後的效果純粹驗證支援 FB 登入是可行的,收工 XD

2019年6月18日 星期二

Google API 筆記 - 使用 Google OAuth 2.0 與 IdToken 和 People API 取得 Email address

大概在 2015 年開發的 Google OAuth2 登入流程 已經需要更新了。當初一直靠 Google Plus API 取得用戶的 Email (GMail) 資訊,結果 Google+ APIs 已經在 2019/03/07 領便當了
https://developers.google.com/+/integrations-shutdown
停用 Google+ 整合服務
2019 年 3 月 7 日起,所有網站上與行動應用程式中的 Google+ 整合功能將全部停止運作。詳細情形如下:
網路整合 (例如外掛程式與互動訊息) 將停止提供服務。如果網站擁有者未採取任何行動,網站的版面配置和/或功能可能會受到影響。
行動應用程式整合 (例如 +1 按鈕、分享到 Google+ 與應用程式活動) 將停止運作。
我們將從 1 月下旬起逐漸停用相關功能。最早從 2019 年 1 月 29 日起,網站與行動應用程式整合功能會偶爾發生失敗的情形。
我們強烈建議開發人員儘快從其網站上和/或行動應用程式中移除相關程式碼。我們也將陸續停用 Google+ API 和 Google+ 登入功能。詳情請參閱這份額外
通知。
雖然我們即將停用 Google+ 一般使用者版本,但我們同時致力為企業機構 提供 Google+ 服務。Google+ 即將換上全新風貌並加入新功能,如需詳細資訊, 請參閱這篇網誌文章
原先是靠這 Google Plus API 取得 Email address:

<?php
$profile_ret = @json_decode(file_get_contents('https://www.googleapis.com/plus/v1/people/me?'.http_build_query( array(
'access_token' => $access_token,
))), true);


現在就改靠 People API:https://developers.google.com/people/api/rest/v1/people/get

<?php
$profile_ret =  @json_decode(file_get_contents('https://people.googleapis.com/v1/people/me?'.http_build_query( array(
'personFields' => 'names,nicknames,emailAddresses,coverPhotos,photos',
'access_token' => $access_token,
))), true);


在 2019 年 06 月,這隻 Google Plus api : https://www.googleapis.com/plus/v1/people/me 仍正常工作著,說不定它就真的是一直從 People API 服務著。

除此之外,原先 Google OAuth2 已經推薦改用 IdToken 進行認證,若是走 IdToken 時,可以在當下就拿到 Email Address 了:

<?php

require_once 'vendor/autoload.php';

$client = new Google_Client();
$client->setClientId($oauth_project_client_id);
$client->setClientSecret($oauth_project_secret_key);
$client->setAccessType("offline");
$client->addScope(['email','profile']);
$client->setRedirectUri($oauth_callback_url);

$token = $client->fetchAccessTokenWithAuthCode($code);
$token_data = $client->verifyIdToken();

$uid = $token_data['sub'];
$email = isset($token_data['email_verified']) && $token_data['email_verified'] ?$token_data['email'] : NULL;


如此就搞定取得用戶 Email address 的項目了!

其他筆記:

$ curl -s 'https://people.googleapis.com/v1/people/me?personFields=names%2Cnicknames%2CemailAddresses%2CcoverPhotos&access_token=USER_ACCESS_TOKEN'
{
  "resourceName": "people/UID",
  "etag": "XXXXXXXXXXXX",
  "names": [
    {
      "metadata": {
        "primary": true,
        "source": {
          "type": "PROFILE",
          "id": "UID"
        }
      },
      "displayName": "NICKNAME",
      "familyName": "LAST_NAME",
      "givenName": "FIRST_NAME",
      "displayNameLastFirst": "LAST_NAME, FIRST_NAME"
    }
  ],
  "coverPhotos": [
    {
      "metadata": {
        "primary": true,
        "source": {
          "type": "PROFILE",
          "id": "UID"
        }
      },
      "url": "https://XXX.googleusercontent.com/cXXXXXXX",
      "default": true
    }
  ],
  "emailAddresses": [
    {
      "metadata": {
        "primary": true,
        "verified": true,
        "source": {
          "type": "ACCOUNT",
          "id": "UID"
        }
      },
      "value": "USER_EMAIL@gmail.com"
    }
  ]
}

2018年4月3日 星期二

[PHP] 微信開放平台開發筆記 - WeChat Web 應用與 OAuth2 client

今年才感到 Wechat app 崛起,得知用戶已破10億,甚至微信支付交易筆數早已超車支付寶1.5倍,已乃覺三十里 Orz 想要用境外身份申請,才發現很多都辦不成,像是境外要用公司身份才行,甚至騰訊公開平台的管理者都還得綁有中國銀行卡(金融卡)才搞得定 <囧> 多虧對岸同事的幫忙,可以小試身手一下。

騰訊公開平台的 OAuth2 文件: https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN

需要的留意的是騰訊公開平台的 Web 應用只允許填入一個 hostname/domain 作為 callback handler ,所以,也有人想得很快,透過在統一地方處理完畢後,在拋去其他地方,如:https://github.com/HADB/GetWeixinCode

在此利用一樣的架構,不過是在 backend 處理 XD 主要是服務常分成 production/alpha/dev site,就把它統一建構在 Production site ,但 Dev site 要登入時,跳去 production site 處理後,再把資料回拋到 dev site(當然也可以申請多個 WeChat Web 應用,每個 site 擁有自己的 Web app)

整個過程都算順利,唯一不太順的地方是 OAuth state 這個參數的使用,原先埋了要跳去其他地方的 callback url 或其他資訊,但測了幾輪發現 state 內若有一些敏感資訊(&)時,回來都會出錯,於是就多加個 base64_encode 來解了(也可以考慮把必要的資料儲存在 cookie)

發動處:

<?php

$init_url = 'https://open.weixin.qq.com/connect/qrconnect?'. http_build_query( array(
        'scope' => 'snsapi_login,snsapi_userinfo',
        'response_type' => 'code',
        'redirect_uri' => 'https://auth.my-domain/wechat/callback',
        'state' => base64_encode( http_build_query(array(
                'give_me_code' => 1,
                'callback' => 'https://service.my-domain/wechat/handle-code',
        )) ),
        'appid' => $weixin_app_id,
));


負責處理 WeChat OAuth2 回傳資料(code):https://auth.my-domain/wechat/callback

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/sns/oauth2/access_token');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( array(
'appid' => $weixin_app_id,
'secret' => $weixin_app_secret,
'code' => $code,
'grant_type' => 'authorization_code',
)));
$ret = @json_decode(curl_exec($ch), true);
             
$state = $_GET['state'];
$state_param = array();
if (!empty($state)) {
$state = @base64_decode($state);
parse_str($state, $state_param);
}

isset($state_param['callback']) && (
preg_match('#http[s]://(.*?)\.my-domain/#i', $state_param['callback'], $match)
) ) {
if (!empty($_GET['code'])) {
if (isset($state_param['give_me_code']) && $state_param['give_me_code'] == '1')
header('Location: '.$state_param['callback'].'?'.http_build_query(array('code' => $_GET['code'])) );
// ...
} else {
header('Location: '.$state_param['callback'].'?'.http_build_query(array('error' => 'no code')) );
}
return;
}


處理 code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/sns/oauth2/access_token');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( array(
'appid' => $weixin_app_id,
'secret' => $weixin_app_secret,
'code' => $ret_code,
'grant_type' => 'authorization_code',
)));

$ret = @json_decode(curl_exec($ch), true);

if (isset($ret['access_token']) && isset($ret['refresh_token']) && isset($ret['openid']) && isset($ret['unionid'])) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/sns/userinfo');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( array(
'access_token' => $ret['access_token'],
'openid' => $ret['openid'],
)));
$profile_ret = @json_decode(curl_exec($ch), true);
}

// $profile_ret['nickname']
// $profile_ret['headimgurl']


原先在 callback handler 上,順便做完 code 檢驗,但後來覺得這樣要傳出去的資料太多(且感到不安),所以還是統一把 code 拋出去,缺點是其他服務就必須都紀錄 WeChat Web 應用的資料(app_id/secret_key)等等,但可以避免受到 DNS 攻擊而把用戶的 access_token 給了出去。

2015年6月29日 星期一

phpBB3 - 使用 OAuth 登入時,自動添加 phpBB3 系統使用者帳號

phpBB3 提供 OAuth 登入的功能,預設有 Bitly、Facebook 跟 Google+ 服務可作為登入系統。只需在外頭管理介面將帳號認證方式從預設的 Db 改成 oauth,接著只要有填寫 api_key, secret_key 後,網頁端在 login 介面下,就會顯示出額外的 OAuth 登入了!

然而,phpBB3 這邊的規劃:凡事透過 OAuth 登入者,完成登入後還要綁定到 PHPBB3 內部帳號才可以。看得出來可能的影響問題,包含資安等等的。而比較重要的一點是 PHPBB3 帳號底層用 Email 帳號當作獨一無二的 key。

因此,如果想要自動建立帳號,需確保 Email 是獨一無二的資料,這邊就簡單的做個小動作:

1.當使用者完成 OAuth 認證後,使用該服務資訊做出一個 unique email address,例如是 facebook.com 登入的,就拿 fb graph id 再加 graph.facebook.com 拼湊一個 email address:uid@graph.facebook.com  而非拿使用者的資料。
2.建立帳號還需要 username 資訊、phpBB3 group id
3.進行 oauth 帳號與 phpBB3 綁定 (link_account_perform_link)

主體上需改變:phpbb/auth/provider/oauth/oauth.php ,我這邊再埋個小東西,當 oauth provider 有提供 get_user_info 時,才進行自動綁定。

對 phpbb/auth/provider/oauth/oauth.php 的操作:

在 public function login($username, $password) 添加東西即可:

if ($this->request->is_set('code', \phpbb\request\request_interface::GET))
{
$this->service_providers[$service_name]->set_external_service_provider($service);
$unique_id = $this->service_providers[$service_name]->perform_auth_login();

// Check to see if this provider is already assosciated with an account
$data = array(
'provider' => $service_name_original,
'oauth_provider_id' => $unique_id
);
$sql = 'SELECT user_id FROM ' . $this->auth_provider_oauth_token_account_assoc . '
WHERE ' . $this->db->sql_build_array('SELECT', $data);
$result = $this->db->sql_query($sql);
$row = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);

// 添加自動建立帳號流程 -- begin
if (!$row && method_exists($this->service_providers[$service_name], 'get_user_info') && ($user_info = $this->service_providers[$service_name]->get_user_info()))
{
$new_user_data = $this->user_row($user_info['username'], $user_info['user_email']);
// create user automatic
if (!function_exists('user_add'))
{
include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
}
$user_id = user_add($new_user_data);

$data = array(
'user_id' => $user_id,
'provider' => $service_name_original,
'oauth_provider_id' => $unique_id,
);
$this->link_account_perform_link($data);

// Update token storage to store the user_id
$storage->set_user_id($user_id);

$sql = 'SELECT user_id, username, user_password, user_passchg, user_email, user_type, user_login_attempts
FROM ' . $this->users_table . '
WHERE user_id = ' . (int) $user_id;
$result = $this->db->sql_query($sql);
$row = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);

if (!$row)
{
throw new \Exception('AUTH_PROVIDER_OAUTH_ERROR_INVALID_ENTRY');
}

// The user is now authenticated and can be logged in
return array(
'status' => LOGIN_SUCCESS,
'error_msg' => false,
'user_row' => $row,
);
}
// 添加自動建立帳號流程 -- end

...


新增一個函數 user_row ,此參考 phpbb/auth/provider/apache.php - private function user_row($username, $password):

private function user_row($username, $user_email)
{
// first retrieve default group id
$sql = 'SELECT group_id
FROM ' . GROUPS_TABLE . "
WHERE group_name = '" . $this->db->sql_escape('REGISTERED') . "'
AND group_type = " . GROUP_SPECIAL;
$result = $this->db->sql_query($sql);
$row = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);

if (!$row)
{
trigger_error('NO_GROUP');
}

// generate user account data
return array(
'username' => $username,
'user_password' => $user_email,
'user_email' => $user_email,
'group_id' => (int) $row['group_id'],
'user_type' => USER_NORMAL,
'user_ip' => $this->user->ip,
'user_new' => ($this->config['new_member_post_limit']) ? 1 : 0,
);
}


如此一來,當使用者透過 oauth 登入時,第一時間若發現沒有系統對應帳號時,會自動建立一組帳號跟 oauth 帳號綁定,而下次再登入時就會因為已經有帳號綁定而登入動作。而 oauth provider 需要添加一個 get_user_info 的函數,以 facebook 來看就是修改 phpbb/auth/provider/oauth/service/facebook.php 檔案:

public function get_user_info()
{
if (!($this->service_provider instanceof \OAuth\OAuth2\Service\Facebook))
{
throw new exception('AUTH_PROVIDER_OAUTH_ERROR_INVALID_SERVICE_TYPE');
}
// This was a callback request, get the token
$this->service_provider->requestAccessToken($this->request->variable('code', ''));
// Send a request with it
$result = json_decode($this->service_provider->request('/me'), true);
if (isset($result['id']) && isset($result['name']))
return array( 'username' => $result['name'] , 'user_email' => $result['id'].'@graph.facebook.com' );
// Return the unique identifier
return NULL;

}

2015年5月22日 星期五

Google API 筆記 - 使用 Google OAuth 2.0 API @ Ubuntu 14.04, PHP 5.5


準備替服務整合 Google Plus 登入方式,因此研究了一下 Google OAuth 2.0 API 的用法:
  • 在 Google Developer Console 建立一個 Google Project
  • 開啟此 Google Project 的 OAuth 使用,並設置"重新導向 URI",此處 URI 雖然不支援萬用符號,但支援輸入多筆,還算夠用。
整個過程下來,得到 client_id、client_secret 兩筆資料,如此一來就可以進行 OAuth 使用:

先組出 Google OAuth 所需的網址提供使用者授權,需要填寫 scope, response_type, redirect_uri, access_type, approval_prompt, client_id,例如:

$init_url = 'https://accounts.google.com/o/oauth2/auth?'. http_build_query( array(
'scope' => 'email profile',
'response_type' => 'code',
'redirect_uri' => $google_oauth_callback_url,
'access_type' => 'offline',
'approval_prompt' => 'force',
'client_id' => $google_project_client_id,
));
header('Location: '.$init_url);


接著,在 callback_url 的網頁中,接了 Google OAuth 回傳的 code 後,從 server site 發 requests 進行處理:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v3/token');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( array(
'client_id' => $google_project_client_id,
'client_secret' => $google_project_secret_key,
'code' => $google_ret_code,
'grant_type' => 'authorization_code',
'redirect_uri' => $google_oauth_callback_url,
)));
$ret = @json_decode(curl_exec($ch), true);


若一切順利的話,在 $ret 中,就可以拿到 access_token 了(此例需開啟 Google+ API)

$profile = @json_decode(file_get_contents('https://www.googleapis.com/plus/v1/people/me?'.http_build_query( array(
'access_token' => $ret['access_token']
))), true);

print_r($profile);


最後,若測試完後,想要替自己用的 Google account 刪除 app 授權的話,可以這邊刪除:

https://security.google.com/settings/security/permissions?pli=1

2015年3月10日 星期二

Facebook 開發筆記 - 使用單一 Facebook app 仿 OAuth 架構提供單多平台多 app 登入使用

由於 Facebook app 在任何平台上,只能允許一個 app,例如 iOS platform 就只能綁定一個 iOS app,如果想要多個 iOS app 都用同一款 Facebook app 時,就出現了這奇妙的需求 :P

因此,再次包裝的方式,那就是用 UIWebview/WebView 來解吧!對於任何一款 Mobile app 都是採用 Browser 來完成登入的。而 Backend service 是維持採用同一款 Facebook app。

原理:主體是以 Facebook Javascript SDK 來使用,當完成 Facebook app 登入認證後,將 Javascript 端取得的 Facebook app token 丟給 backend service ,驗證後交換成自家 service token,未來用自己的 service token 來進行服務互動。

以上狀態僅需依照 Facebook SDK Javascript 文件已經可以完成大半了:

FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    console.log('get facebook app token');
  }
  else {
    FB.login();
  }
});


在 response.status === 'connected' 就能取得 facebook token,再轉呼叫自家 service 來交換 token 即可收工。

然而?事情不是那麼簡單的 XD 在 mobile platform 環境上,用 chrome browser 或是 safari 都可以正常工作,唯獨 PhoneGap 等類似架構會出錯,主因是 Facebook SDK Javascript 登入時,會彈跳視窗,結束後可以再導回來,但在 PhoneGap 架構上,可能受限於沒有分頁機制而出錯?總之,解法:自行用 direct_url 跟 Facebook 互動吧!這招印象中是在寫 server side 的用法:

當使用者點擊 login 時,不要用 Facebook Javascript SDK,而是將網址導向到:

https://www.facebook.com/dialog/oauth?client_id=YourFacebookAppID&redirect_uri=http://localhostOrServiceWebURL/&response_type=token&scope=publish_stream,email

當使用者完成登入後,將導回你指定的位置,而這時在 FB.getLoginStatus 時,又可以正常取得 response.status === 'connected' 等資訊了。