日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

【学无止境】 基于ThinkPHP的OAuth2.0实现 ----OAuth2.0 个人学习笔记 Two

發布時間:2025/5/22 php 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【学无止境】 基于ThinkPHP的OAuth2.0实现 ----OAuth2.0 个人学习笔记 Two 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

ThinkPHP 結合 OAuth2.0

準備工作

  • 第一我們得準備好OAuth2.0的源碼包,下載地址點這里。

  • 我們將下載好的源碼包放在thinkphp的vendor文件夾下面。這里注意只要src文件夾下的OAuth2放入vendor即可。如下圖:

  • 新建模塊oauth2.0 然后將其路由等信息配置完畢。

  • 開始工作


    • 首先還是在配置文件中把OAuth的PDO數據庫配置完成
    //OAuth數據庫配置'OAUTH_DB_HOST'=>'xxxxx.com','OAUTH_DB_NAME'=>'xxx','OAUTH_DB_USER'=>'xxx','OAUTH_DB_PWD'=>'xxxxxxxx',
    • 新建 IndexController 作為本次學習的主控制器,注意本控制器請繼承 RestController(thinkphp封裝)
    class IndexController extends RestController
    • 新建 authorize 公共方法來處理用戶的授權請求和換取code的工作
    public function authorize(){//默認response_type為code$_GET['response_type'] = isset($_GET['response_type'])?$_GET['response_type']:'code';//數據表字段為client_id指的是appidisset($_GET['appid']) && $_GET['client_id'] = $_GET['appid'];$oauth = new OAuthModel();$request = \OAuth2\Request::createFromGlobals();$response = new \OAuth2\Response();if (!$oauth->server()->validateAuthorizeRequest($request, $response)) {$response->send();exit();}//用戶同意授權后$is_authorized = ($_POST['authorized'] == 'yes');//生成code(綁定你的業務user_id)$oauth->server()->handleAuthorizeRequest($request, $response, $is_authorized,$user_id);if ($is_authorized) {$code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);//返回第三方服務//所帶參數state,code,$parses = $_REQUEST;$back_parses = array('state'=>$parses['state'],'code'=>$code,);//跳轉回第三方服務器if(!$parses['redirect_url']) $this->err("redirect_url丟失!");redirect( base64_decode($parses['redirect_url']) . '?' . http_build_query($back_parses));}else{$parses = $_GET;$back_parses = array('state'=>$parses['state'],);//跳轉回第三方服務器redirect( urldecode($parses['redirect_url']) . '?' . http_build_query($back_parses) );}}
    • 獲取到了code之后我們需要拿著這個code去換token,新建公共方法token 完成以下工作
    public function token(){//默認grant_type為authorization_code(授權碼模式)$_POST['grant_type'] = isset($_POST['grant_type'])?$_POST['grant_type']:'authorization_code';$oauth = new OAuthModel();$oauth->server()->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send(); }
    • 拿到了這個token后我們就要校驗這個token是否是正確的token,這個時候回到我們自己的項目目錄下新建 CheckTokenController 控制器。
    class CheckTokenController extends BaseController {protected function _initialize(){parent::_initialize();$oauth = new OAuthModel();if(!$_REQUEST['access_token']){$this->err("未找到access_token,請確認已傳入access_token");}//驗證access_tokenif (!$oauth->server()->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {$oauth->server()->getResponse()->send();exit();}//刪除不必要的GET參數unset($_GET['m']);unset($_GET['c']);unset($_GET['a']);unset($_GET['access_token']);} }

    所有的項目資源控制器必須繼承該控制器!!!

    • 最后一步,回到自己的資源控制器里面編寫自己的邏輯代碼
    class UserController extends CheckAccessTokenController {public function user_info(){switch ($this->_method){case 'get':$model = new UserModel();$this->suc("用戶信息獲取成功",$model->user_info($this->user_id));break;case 'post'://數據更新:使用動態驗證,驗證數據合法性同時驗證數據是更新還是插入//TODO:當數據為更新時一定注意須包含主鍵id,否則將自動判斷為插入數據//動態驗證,邏輯代碼}}}

    測試方法舉例

    當我們完成整個編寫流程后我們需要如何去測試呢? 在這里我也提供一個測試的方法與大家共享

    • 將用戶導向授權層獲取code
    public function user(){$url = "http://xxxxxx/resource/user/access_token/". $this->get_oauth_token() ;$this->test($url);}
    • 檢查是否有token
    public function get_oauth_token(){if($code = $_GET['code']){//TODO::驗證返回的state 防止CSRF攻擊$code = $_GET['code'];$res = $this->code2oauthtoken($code);if($res->access_token){return $res->access_token;}else{echo "無效的code";exit();}}else{$this->redirect_oauth();}} protected function redirect_oauth($url){$url = $url?:get_url();//TODO::使用state參數防止CSRF攻擊 當用戶跳轉到授權服務器前,使用session儲存state,當用戶跳轉回來時,比對state,以此判斷用戶身份是否改變redirect('http://xxxxxxx/oauth2.0/authorize/appid/testclient/state/xyz/redirect_url/'.base64_encode($url));}
    • 成功拿回code 拿code 換取 token
    public function code2oauthtoken($code){$url = 'xxxxxx/oauth2.0/token';//$url =ROOT_URL . U('Home/Index/token');$method = 'post';$param = array('grant_type'=>'authorization_code','code'=>$code,);$header = array('Authorization: Basic ' .base64_encode(self::APPID . ':' . self::APPSECRET),);$res = http_request($url,$method,$param,$header);$res = json_decode($res);return $res;}
    • 最終獲取資源層資源
    { "error": 0, "message": "數據拿出成功", "data": "RE_zjw" }

    總結

    以上是生活随笔為你收集整理的【学无止境】 基于ThinkPHP的OAuth2.0实现 ----OAuth2.0 个人学习笔记 Two的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。