美文网首页
PHP 关于Oauth认证,授权

PHP 关于Oauth认证,授权

作者: Mracale | 来源:发表于2021-08-25 15:46 被阅读0次

    安装OAuth2.0 php包

    OAuth官网提供了很多第三方包,详见网站https://oauth.net/code/http://bshaffer.github.io/oauth2-server-php-docs/cookbook/

    链接:https://pan.baidu.com/s/1ukRiSa5ftOVyz6NEXoqOrg
    提取码:estb

    下载后解压,我们只需要将里面/src/OAuth文件夹整个拷贝到tp5/extend/目录下,就可以自动注册对应的命名空间。之后我们就可以使用\OAuth2...的方式去使用OAuth里面的任何方法。

    创建数据库

    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    
    -- ----------------------------
    -- Table structure for oauth_access_tokens
    -- ----------------------------
    DROP TABLE IF EXISTS `oauth_access_tokens`;
    CREATE TABLE `oauth_access_tokens`  (
      `access_token` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
      `client_id` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
      `user_id` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `expires` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0),
      `scope` varchar(4000) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      PRIMARY KEY (`access_token`) USING BTREE
    ) ENGINE = MyISAM CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Table structure for oauth_authorization_codes
    -- ----------------------------
    DROP TABLE IF EXISTS `oauth_authorization_codes`;
    CREATE TABLE `oauth_authorization_codes`  (
      `authorization_code` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
      `client_id` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
      `user_id` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `redirect_uri` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `expires` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0),
      `scope` varchar(4000) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `id_token` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      PRIMARY KEY (`authorization_code`) USING BTREE
    ) ENGINE = MyISAM CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Table structure for oauth_clients
    -- ----------------------------
    DROP TABLE IF EXISTS `oauth_clients`;
    CREATE TABLE `oauth_clients`  (
      `client_id` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
      `client_secret` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `redirect_uri` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `grant_types` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `scope` varchar(4000) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `user_id` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      PRIMARY KEY (`client_id`) USING BTREE
    ) ENGINE = MyISAM CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Table structure for oauth_jwt
    -- ----------------------------
    DROP TABLE IF EXISTS `oauth_jwt`;
    CREATE TABLE `oauth_jwt`  (
      `client_id` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
      `subject` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `public_key` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL
    ) ENGINE = MyISAM CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Table structure for oauth_refresh_tokens
    -- ----------------------------
    DROP TABLE IF EXISTS `oauth_refresh_tokens`;
    CREATE TABLE `oauth_refresh_tokens`  (
      `refresh_token` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
      `client_id` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
      `user_id` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `expires` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0),
      `scope` varchar(4000) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      PRIMARY KEY (`refresh_token`) USING BTREE
    ) ENGINE = MyISAM CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Table structure for oauth_scopes
    -- ----------------------------
    DROP TABLE IF EXISTS `oauth_scopes`;
    CREATE TABLE `oauth_scopes`  (
      `scope` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
      `is_default` tinyint(1) NULL DEFAULT NULL,
      PRIMARY KEY (`scope`) USING BTREE
    ) ENGINE = MyISAM CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Table structure for oauth_users
    -- ----------------------------
    DROP TABLE IF EXISTS `oauth_users`;
    CREATE TABLE `oauth_users`  (
      `username` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `password` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `first_name` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `last_name` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `email` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
      `email_verified` tinyint(1) NULL DEFAULT NULL,
      `scope` varchar(4000) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL
    ) ENGINE = MyISAM CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
    
    
    INSERT INTO oauth_clients (client_id, client_secret, redirect_uri) VALUES ("testclient", "testpass", "http://fake/");
    
    

    创建控制器Oauth.php

    <?php
    namespace app\auth\controller;
    use think\Controller;
    
    class Oauth extends Controller
    {
        /** 认证授权获取code
        **  http://my.tpf.com/authorize.html?response_type=code&client_id=testclient&state=xyz
        **/
        public function authorize()
        {
            // echo 11;die;
            global $server;
            $dsn      = 'mysql:dbname=tpf;host=127.0.0.1';
            $username = 'root';
            $password = 'xxxxx';
            \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
            //echo 33;die;
            if (!$server->validateAuthorizeRequest($request, $response)) {
                $response->send();
                die;
            }
            // display an authorization form
            // echo 22;die;
            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>');
            }
            // echo 11;die;
            // 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();
        }
    
        /** 
            通过code 获取 token
        **  http://my.tpf.com/token.html
            @param grant_type : authorization_code
            @param code : code
            @param client_id : testclient
            @param client_secret : testpass
        **/
        public function token(){
            global $server;
            $dsn      = 'mysql:dbname=tpf;host=127.0.0.1';
            $username = 'root';
            $password = 'xxxxxxx';
            \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();   
        }
    
        /** 
            通过code 获取 token
        **  http://my.tpf.com/resource.html
            @param access_token : access_token
        **/
        public function resource()
        {
            // include our OAuth2 Server object
            global $server;
            $dsn      = 'mysql:dbname=tpf;host=127.0.0.1';
            $username = 'root';
            $password = 'xxxxx';
     
            \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!'));
        }
    }
    

    配置路由信息 router.php

    'authorize' => ['auth/Oauth/authorize', ['method' => 'GET|POST']],
    'token' => ['auth/Oauth/token', ['method' => 'GET|POST']],
    'resource' => ['auth/Oauth/resource', ['method' => 'GET|POST']],
    
    image.png

    测试

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

    http://localhost/authorize.html?response_type=code&client_id=testclient&state=xyz

    1. 通过code 获取 token
      http://localhost/token.html
      grant_type:authorization_code
      code:code
      client_id:testclient
      client_secret:testpass
    image.png
    1. 通过token 获取 资源信息
      http://my.tpf.com/resource.html
      access_token:上面获取的access_token
      image.png

    相关文章

      网友评论

          本文标题:PHP 关于Oauth认证,授权

          本文链接:https://www.haomeiwen.com/subject/hfteiltx.html