php 实现oauth2.0 tp方案(转)


1.  下载 oauth2-server-php 地址:https://github.com/bshaffer/oauth2-server-php
2.  解压/src/OAuth文件夹整个拷贝到tp5/extend/目录下
3. 创建数据库
由于我们之前下载的OAuth包有用到很多数据表,所以需要按照其要求创建好数据表,创建代码如下:

CRE ATE TAB LE oauth_clients (
  client_id             VARCHAR(80)   NOT NULL,
  client_secret         VARCHAR(80),
  redirect_uri          VARCHAR(2000),
  grant_types           VARCHAR(80),
  scope                 VARCHAR(4000),
  user_id               VARCHAR(80),
  PRIMARY KEY (client_id)
);
 
CRE ATE TAB LE oauth_access_tokens (
  access_token         VARCHAR(40)    NOT NULL,
  client_id            VARCHAR(80)    NOT NULL,
  user_id              VARCHAR(80),
  expires              TIMESTAMP      NOT NULL,
  scope                VARCHAR(4000),
  PRIMARY KEY (access_token)
);
 
CRE ATE TAB LE oauth_authorization_codes (
  authorization_code  VARCHAR(40)     NOT NULL,
  client_id           VARCHAR(80)     NOT NULL,
  user_id             VARCHAR(80),
  redirect_uri        VARCHAR(2000),
  expires             TIMESTAMP       NOT NULL,
  scope               VARCHAR(4000),
  id_token            VARCHAR(1000),
  PRIMARY KEY (authorization_code)
);
 
CRE ATE TAB LE oauth_refresh_tokens (
  refresh_token       VARCHAR(40)     NOT NULL,
  client_id           VARCHAR(80)     NOT NULL,
  user_id             VARCHAR(80),
  expires             TIMESTAMP       NOT NULL,
  scope               VARCHAR(4000),
  PRIMARY KEY (refresh_token)
);
 
CRE ATE TAB LE oauth_users (
  username            VARCHAR(80),
  password            VARCHAR(80),
  first_name          VARCHAR(80),
  last_name           VARCHAR(80),
  email               VARCHAR(80),
  email_verified      BOOLEAN,
  scope               VARCHAR(4000)
);
 
CRE ATE TAB LE oauth_scopes (
  scope               VARCHAR(80)     NOT NULL,
  is_default          BOOLEAN,
  PRIMARY KEY (scope)
);
 
CRE ATE TAB LE oauth_jwt (
  client_id           VARCHAR(80)     NOT NULL,
  subject             VARCHAR(80),
  public_key          VARCHAR(2000)   NOT NULL
);

所以第一步是实现authorization。

我们在之前创建好的控制器中添加一个函数authorize()

代码如下(注意,dbname需要换成你自己的数据库的名字,下同):

<?php
namespace app\index\controller;
 
class OAuth extends \think\Controller
{
    public function authorize()
    {
        global $server;
        $dsn      = 'mysql:dbname=XXX;host=127.0.0.1';
        $username = 'root';
        $password = '';
        \OAuth2\Autoloader::register();
 
        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
 
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $server = new \OAuth2\Server($storage);
 
        // 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));
 
 
        $request = \OAuth2\Request::createFromGlobals();
        $response = new \OAuth2\Response();
 
        // validate the authorize request
        if (!$server->validateAuthorizeRequest($request, $response)) {
            die;
        }
        // display an authorization form
        if (empty($_POST)) {
          exit('
        <form method="post">
          <label>Do You Authorize TestClient?</label><br />
          <input type="submit" name="authorized" value="yes">
          <input type="submit" name="authorized" value="no">
        </form>');
        }
 
        // print the authorization code if the user has authorized your client
        $is_authorized = ($_POST['authorized'] === 'yes');
        $server->handleAuthorizeRequest($request, $response, $is_authorized);
        if ($is_authorized) {
          // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client
          $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
          exit("SUCCESS! Authorization Code: $code");
        }
        $response->send();
    }
}
在tp5/route/route.php中创建相应路由,post方法和get方法都创建

Route::get('authorize', 'OAuth/authorize');
Route::post('authorize', 'OAuth/authorize');
接下来验证创建的authorize是否成功,通过以下链接去访问,在浏览器中输入以下链接,回车后就会显示一个验证表单,当你点击yes按钮后,如果窗口显示一串字符,那么就表示authorize创建成功了,这串字符就是code,接下来需要通过这个code去获取token。

http://localhost/authorize.php?response_type=code&client_id=testclient&state=xyz
3.4 实现token申请方法

在OAuth.php控制器中添加函数token(),代码如下

public function token(){
        global $server;
        $dsn      = 'mysql:dbname=XXX;host=127.0.0.1';
        $username = 'root';
        $password = '';
        \OAuth2\Autoloader::register();
 
        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
 
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $server = new \OAuth2\Server($storage);
 
        // 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));
 
        
        // Handle a request for an OAuth2.0 Access Token and send the response to the client
        $server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();   
    }
在tp5/route/route.php中创建相应路由,post方法和get方法都创建

Route::get('token', 'OAuth/token');
Route::post('token', 'OAuth/token');
在测试是否获取token之前,我们需要在oauth_clients表中加一条数据,可执行如下SQL:

INSERT INTO oauth_clients (client_id, client_secret, redirect_uri) VALUES ("testclient", "testpass", "http://baidu/");

curl -u testclient:testpass http://localhost/token.php -d 'grant_type=authorization_code&code=YOUR_CODE'
如果成功的话,你应该会得到access token,如下内容

{"access_token":"6f05ad622a3d32a5a81aee5d73a5826adb8cbf63","expires_in":3600,"token_type":"bearer","scope":null}
3.5 实现Resource获取

 在OAuth.php控制器中添加函数resource(),代码如下

public function resource()
    {
        // include our OAuth2 Server object
        global $server;
        $dsn      = 'mysql:dbname=XXX;host=127.0.0.1';
        $username = 'root';
        $password = '';
 
        \OAuth2\Autoloader::register();
 
        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
 
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $server = new \OAuth2\Server($storage);
 
        // 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));
 
 
        // Handle a request to a resource and authenticate the access token
        if (!$server->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {
            $server->getResponse()->send();
            die;
        }
        echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));
    }
在tp5/route/route.php中创建相应路由,post方法和get方法都创建

Route::get('resource', 'OAuth/resource');
Route::post('resource', 'OAuth/resource');

curl http://localhost/resource.php -d 'access_token=YOUR_TOKEN'
如果成功,将会获得以下响应:

{"success":true,"message":"You accessed my APIs!"}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值