当前位置: 首页 > news >正文

OAuth2 基于TP 搭建简单案例

阅读须知:理解OAuth2

OAuth是一个关于授权(authorization)的开放网络标准,在全世界得到广泛应用,目前的版本是2.0版。今天就试着把环境搭建一下在此仅作为学习记录;

参考资料来源:

http://oauth.net/2/

http://bshaffer.github.io/oauth2-server-php-docs/cookbook/

数据表准备:

--
-- 表的结构 `oauth_access_tokens`
--

CREATE TABLE IF NOT EXISTS `oauth_access_tokens` (
  `access_token` text,
  `client_id` text,
  `user_id` text,
  `expires` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `scope` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- 表的结构 `oauth_authorization_codes`
--

CREATE TABLE IF NOT EXISTS `oauth_authorization_codes` (
  `authorization_code` text,
  `client_id` text,
  `user_id` text,
  `redirect_uri` text,
  `expires` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `scope` text,
  `id_token` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- 表的结构 `oauth_clients`
--

CREATE TABLE IF NOT EXISTS `oauth_clients` (
  `client_id` text,
  `client_secret` text,
  `redirect_uri` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- 转存表中的数据 `oauth_clients`
--

INSERT INTO `oauth_clients` (`client_id`, `client_secret`, `redirect_uri`) VALUES
('demoapp', 'demopass', 'http://127.0.0.1/tp/index.php');

-- --------------------------------------------------------

--
-- 表的结构 `oauth_public_keys`
--

CREATE TABLE IF NOT EXISTS `oauth_public_keys` (
  `client_id` varchar(80) DEFAULT NULL,
  `public_key` varchar(8000) DEFAULT NULL,
  `private_key` varchar(8000) DEFAULT NULL,
  `encryption_algorithm` varchar(80) DEFAULT 'RS256'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- 表的结构 `oauth_refresh_tokens`
--

CREATE TABLE IF NOT EXISTS `oauth_refresh_tokens` (
  `refresh_token` text,
  `client_id` text,
  `user_id` text,
  `expires` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `scope` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- 表的结构 `oauth_scopes`
--

CREATE TABLE IF NOT EXISTS `oauth_scopes` (
  `scope` text,
  `is_default` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- 表的结构 `oauth_users`
--

CREATE TABLE IF NOT EXISTS `oauth_users` (
  `username` varchar(255) NOT NULL,
  `password` varchar(2000) DEFAULT NULL,
  `first_name` varchar(255) DEFAULT NULL,
  `last_name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Indexes for table `oauth_users`
--
ALTER TABLE `oauth_users`
  ADD PRIMARY KEY (`username`);

 

OAuth2 库地址:https://github.com/bshaffer/oauth2-server-php

这里我把它放在Vendor/OAuth2里;

 

授权请求类:

<?php

namespace Api\Controller;

class OAuth2Controller extends \Org\OAuth2\Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    public function authorize()
    {

// validate the authorize request
        if (!$this->oauth_server->validateAuthorizeRequest($this->oauth_request, $this->oauth_response)) {
            $this->oauth_response->send();
            die;
        }


// print the authorization code if the user has authorized your client
        $this->oauth_server->handleAuthorizeRequest($this->oauth_request, $this->oauth_response, true);

        // 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($this->oauth_response->getHttpHeader('Location'), strpos($this->oauth_response->getHttpHeader('Location'), 'code=') + 5, 40);

        echo json_encode(['code' => $code]);

        //$this->oauth_response->send();
    }

    public function token()
    {
        $this->oauth_server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();
    }

}

 

OAuth2 库的请求封装放在:Org/OAuth2里;

<?php

namespace Org\OAuth2;

class Controller
{

    protected $oauth_server;
    protected $oauth_storage;
    protected $oauth_request;
    protected $oauth_response;

    public function __construct()
    {
        // Autoloading (composer is preferred, but for this example let's just do this)
//        require_once(VENDOR_PATH . '/OAuth2/Autoloader.php');
//        \OAuth2\Autoloader::register();
        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $this->oauth_storage = new \OAuth2\Storage\Pdo(array('dsn' => C('DSN'), 'username' => C('USERNAME'), 'password' => C('PASSWORD')));

        // Pass a storage object or array of storage objects to the OAuth2 server class
        $this->oauth_server = new \OAuth2\Server($this->oauth_storage);

        // Add the "Client Credentials" grant type (it is the simplest of the grant types)
        $this->oauth_server->addGrantType(new \OAuth2\GrantType\ClientCredentials($this->oauth_storage));

        // Add the "Authorization Code" grant type (this is where the oauth magic happens)
        $this->oauth_server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($this->oauth_storage));

        $this->oauth_request = \OAuth2\Request::createFromGlobals();
        $this->oauth_response = new \OAuth2\Response();
    }

}


<?php

namespace Org\OAuth2;

class Resource extends Controller
{

    protected $tokenData;

    public function __construct()
    {
        parent::__construct();

        // Handle a request to a resource and authenticate the access token
        if (!$this->oauth_server->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {
            $this->oauth_server->getResponse()->send();
            die;
        }

        $this->tokenData = $this->oauth_server->getResourceController()->getToken();
    }

}

  

测试类:

<?php

namespace Api\Controller;

class TestController extends \Org\OAuth2\Resource
{

    public function __construct()
    {
        parent::__construct();
    }

    public function test()
    {
        echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));
    }

    public function getToken()
    {
        echo json_encode(['token' => $this->tokenData]);
    }

}

 

配置文件:

require_once(VENDOR_PATH . '/OAuth2/Autoloader.php');
OAuth2\Autoloader::register();
return array(
    //'配置项'=>'配置值'
    'AUTOLOAD_NAMESPACE' => array('OAuth2' => VENDOR_PATH . 'OAuth2/'), //扩展模块列表
    'DSN' => 'mysql:host=localhost;dbname=oauth2',
    'USERNAME' => 'root',
    'PASSWORD' => '',
);

  

转载于:https://www.cnblogs.com/wangyulu/p/5326533.html

相关文章:

  • __OSX_AVAILABLE_STARTING
  • simpson公式求定积分
  • hdu 1166 敌兵布阵(线段树详解)
  • java获取获得Timestamp类型的当前系统时间。
  • 在SQLServer使用触发器实现数据完整性
  • 软件测试学习日志3 ————软件测试作业之控制流图
  • 【bzoj1046】[HAOI2007]上升序列
  • 关于网站优化
  • 全球78707个主要城市数据库,包含经纬度坐标值、国家、省份
  • java 二进制数字符串转换工具类
  • 逻辑数据库设计 - 单纯的树(递归关系数据)
  • web storage 之留言板
  • tablib.Dataset()操作exl类型数据之“类方法”研究
  • 用自己的机器人和ubuntu PC实现通信和控制--26
  • Ubuntu计算文件md5值命令
  • [iOS]Core Data浅析一 -- 启用Core Data
  • 【5+】跨webview多页面 触发事件(二)
  • 【挥舞JS】JS实现继承,封装一个extends方法
  • 【译】React性能工程(下) -- 深入研究React性能调试
  • 【跃迁之路】【641天】程序员高效学习方法论探索系列(实验阶段398-2018.11.14)...
  • 4. 路由到控制器 - Laravel从零开始教程
  • Android路由框架AnnoRouter:使用Java接口来定义路由跳转
  • ES6 ...操作符
  • IE报vuex requires a Promise polyfill in this browser问题解决
  • JavaScript实现分页效果
  • LeetCode18.四数之和 JavaScript
  • leetcode46 Permutation 排列组合
  • vue 配置sass、scss全局变量
  • windows下mongoDB的环境配置
  • 闭包,sync使用细节
  • 搭建gitbook 和 访问权限认证
  • 短视频宝贝=慢?阿里巴巴工程师这样秒开短视频
  • 你真的知道 == 和 equals 的区别吗?
  • 漂亮刷新控件-iOS
  • 使用Maven插件构建SpringBoot项目,生成Docker镜像push到DockerHub上
  • 通过几道题目学习二叉搜索树
  • 我与Jetbrains的这些年
  • 延迟脚本的方式
  • 在Docker Swarm上部署Apache Storm:第1部分
  • AI又要和人类“对打”,Deepmind宣布《星战Ⅱ》即将开始 ...
  • ​七周四次课(5月9日)iptables filter表案例、iptables nat表应用
  • #QT项目实战(天气预报)
  • #经典论文 异质山坡的物理模型 2 有效导水率
  • (1)(1.13) SiK无线电高级配置(五)
  • (react踩过的坑)antd 如何同时获取一个select 的value和 label值
  • (Redis使用系列) SpringBoot 中对应2.0.x版本的Redis配置 一
  • (TOJ2804)Even? Odd?
  • (附源码)springboot 智能停车场系统 毕业设计065415
  • (三)docker:Dockerfile构建容器运行jar包
  • (四) Graphivz 颜色选择
  • **登录+JWT+异常处理+拦截器+ThreadLocal-开发思想与代码实现**
  • .net core 客户端缓存、服务器端响应缓存、服务器内存缓存
  • .NET 同步与异步 之 原子操作和自旋锁(Interlocked、SpinLock)(九)
  • .NET 中各种混淆(Obfuscation)的含义、原理、实际效果和不同级别的差异(使用 SmartAssembly)
  • .NET/C# 项目如何优雅地设置条件编译符号?