關於ThinkPHP5中使用 Auth2 驗證的實現

在tp上實現的auth2驗證的,在網上發現筆記不多, 不像yii, 故在此發表一下筆記,用來幫助有相關需求的朋友php

PS: 鑑於oauth2有四種方案, 本實例是基於 客戶端憑證 實現,其餘三種就不講述了thinkphp

1、經過composer安裝json

composer require --prefer-dist bshaffer/oauth2-server-php瀏覽器

安裝完成後,如圖:
clipboard.png
會出現相關的目錄restful

2、實現受權文件app

1) 建立對應的數據表composer

首先找到 Pdo.php文件,如圖:
clipboard.pngyii

而後找到該位置學習

clipboard.png

目的,是告訴你建立表時的名稱,應該和這裏使用的表名稱一致測試

關於建立的表,我直接上代碼,方便各位能夠直接複製粘貼:

CREATE TABLE oauth_access_tokens (
access_token varchar(40) NOT NULL,
client_id varchar(80) NOT NULL,
user_id int(11) DEFAULT NULL,
expires varchar(19) NOT NULL,
scope text,
PRIMARY KEY (access_token),
KEY fk_access_token_oauth2_client_client_id (client_id),
KEY ix_access_token_expires (expires),
CONSTRAINT fk_access_token_oauth2_client_client_id FOREIGN KEY (client_id) REFERENCES pos_oauth2_client (client_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE oauth_authorization_codes (
authorization_code varchar(40) NOT NULL,
client_id varchar(80) NOT NULL,
user_id int(11) DEFAULT NULL,
redirect_uri text NOT NULL,
expires int(11) NOT NULL,
scope text,
PRIMARY KEY (authorization_code),
KEY fk_authorization_code_oauth2_client_client_id (client_id),
KEY ix_authorization_code_expires (expires),
CONSTRAINT fk_authorization_code_oauth2_client_client_id FOREIGN KEY (client_id) REFERENCES pos_oauth2_client (client_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE oauth_clients (
client_id varchar(80) NOT NULL,
client_secret varchar(80) NOT NULL,
redirect_uri text NOT NULL,
grant_type text,
scope text,
created_at int(11) DEFAULT NULL,
updated_at int(11) DEFAULT NULL,
created_by int(11) DEFAULT NULL,
updated_by int(11) DEFAULT NULL,
PRIMARY KEY (client_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE oauth_refresh_tokens (
refresh_token varchar(40) NOT NULL,
client_id varchar(80) NOT NULL,
user_id int(11) DEFAULT NULL,
expires int(11) NOT NULL,
scope text,
PRIMARY KEY (refresh_token),
KEY fk_refresh_token_oauth2_client_client_id (client_id),
KEY ix_refresh_token_expires (expires),
CONSTRAINT fk_refresh_token_oauth2_client_client_id FOREIGN KEY (client_id) REFERENCES pos_oauth2_client (client_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE oauth_scopes (
scope text,
is_default tinyint(1) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

添加一條數據
insert into oauth_clients(client_id,client_secret,redirect_uri,grant_type,scope,created_at,updated_at,created_by,updated_by) values ('admin','123456','http://','client_credentials',NULL,NULL,NULL,NULL,NULL);

PS,說明一下,如圖:

clipboard.png

在我實際使用中,只使用到這五張表,也就是上面建立的五張表,在這個config裏面,剩下的幾個選項我是所有 註銷掉了的

另外還有一個狀況,說明一下: 有可能各位,對數據表設置了表前綴, 也是須要在此進行相關修改的, 好比我建立的,見圖:

clipboard.png

因此我進行了相關的修改:

clipboard.png

2) 建立受權文件 Oauth2.php, 名字隨便本身取

<?php
namespace appcommon;
/**

  • @author jinyan
  • @create 20180416

*/
use OAuth2StoragePdo;
use thinkConfig;

class Oauth2
{

/**
 * @Register new Oauth2 apply
 * @param string $action
 * @return boolean|\OAuth2\Server
 */
function grantTypeOauth2($action=null)
{
    Config::load(APP_PATH.'database.php');

    $storage = new Pdo(
        [
            'dsn'      => config('dsn'),
            'username' => config('username'),
            'password' => config('password')
        ]
    );

    $server = new \OAuth2\Server($storage, array('enforce_state'=>false));
    // Add the "Client Credentials" grant type (it is the simplest of the grant types)
    $server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage));
    // Add the "Authorization Code" grant type (this is where the oauth magic happens)
    $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($storage));
    // Add the "User Credentials" grant type (this is where the oauth magic happens)
    $server->addGrantType(new \OAuth2\GrantType\UserCredentials($storage));
    return $server;
}

/**
 * @校驗token值
 * @param unknown $server
 */
protected function checkApiAuthroize($server)
{
    if (!$server->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {
        $server->getResponse()->send();
        exit;
    }
}

}
?>

3) 建立token文件, Access.php

<?php
namespace apprestfulcontroller;
use appcommonOauth2;

/**

  • @uathor:jinyan

*/

class Access extends Oauth2
{

protected  $_server;

/**
 * @受權配置
 */
public function __construct()
{
    return $this->_server = $this->grantTypeOauth2();
}

/**
 *
 */
private function _token()
{
    // Handle a request for an OAuth2.0 Access Token and send the response to the client
    $this->_server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send('json', 'oauth2_');
}

/**
 * @get access_token
 */
public function access_token()
{
    $this->_token();
}

}
?>

那麼如何請求一個access_token的值呢? 直接調用這個 acccess_token()的方法便可

request url: http://restful.thinkphp.com/r...

還請得以前建立數據表時,有添加了一條新數據嗎? 其做用就是至關於用來獲取access_token的帳號密碼之類的, 記得須要使用 Post方式獲取token

請求的參數
{

client_id=admin
client_secret=123456
grant_type=client_credentials //這個參數是固定的

}

若是請求成功的話,會返回以下圖所示:

clipboard.png

貼上,經過ff瀏覽器httprequest的請求界面:

clipboard.png

4) 經過 access_token 獲取接口數據 ,Sms.php

<?php
namespace apprestfulcontroller;
/**

  • Created by PhpStorm.
  • User: Administrator
  • Date: 2018/7/29
  • Time: 22:02

*/
use appcommonOauth2;

class Sms extends Oauth2
{

protected $_server;

/**
 * @受權配置
 */
public function __construct()
{
    $this->_server = $this->grantTypeOauth2();
}

public function test()
{
    //access_token驗證
    $this->checkApiAuthroize($this->_server);

    echo '成功請求到數據';
}

}

3、 測試效果如圖:

1)首先不帶access_token請求, test()方法:

clipboard.png

結果出現一個401未驗證經過的狀態

2)而後請求一個錯誤的access_token, test()方法

clipboard.png
一樣是一個401的狀態,但此時,如圖

clipboard.png

有信息返回給咱們

3) 最後,使用一個正確的access_token, test()方法

clipboard.png

因此,基於第1種狀況和第2種狀況,你應該自定一個token未驗證成功的方法,如圖:

clipboard.png

clipboard.png

clipboard.png

clipboard.png

完結。

若有疑問需解答, 請加學習羣 2751786, 謝謝

相關文章
相關標籤/搜索