登录  /  注册
ThinkPHP5中使用 Auth2进行验证的过程分析
不言
发布: 2023-04-03 13:58:02
原创
3776人浏览过

本篇文章给大家分享的内容是关于ThinkPHP5中使用 Auth2进行验证的过程分析,有需要的朋友可以参考一下,希望能帮助到大家。

在tp上实现的auth2验证的,在网上发现笔记很少, 不像yii, 故在此发表一下笔记,用来帮助有相关需求的朋友

PS: 鉴于oauth2有四种方案, 本实例是基于 客户端凭证 实现,其他三种就不讲述了

一、通过composer安装

composer require --prefer-dist bshaffer/oauth2-server-php

安装完成后,如图:
1942990944-5b5e808e57161_articlex.png
会出现相关的目录

二、实现授权文件

1) 创建对应的数据表

首先找到 Pdo.php文件,如图:

95332761-5b5e866ad1dc3_articlex.png

然后找到该位置

2045935780-5b5e86ab3754b_articlex.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,说明一下,如图:

1505044603-5b5e88732e0f8_articlex.png

在我实际使用中,只使用到这五张表,也就是上面创建的五张表,在这个config里面,剩下的几个选项我是全部 注销掉了的

另外还有一个情况,说明一下: 有可能各位,对数据表设置了表前缀, 也是需要在此进行相关修改的, 比如我创建的,见图:

2424443104-5b5e892e8e7d3_articlex.png

所以我进行了相关的修改:

2596200848-5b5ffeceac386_articlex.png

2) 创建授权文件 Oauth2.php, 名字随便自己取

<?phpnamespace 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

<?phpnamespace 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 //这个参数是固定的
}
登录后复制

如果请求成功的话,会返回如下图所示:

676155848-5b5e942626588_articlex.png

贴上,通过ff浏览器httprequest的请求界面:

2575333368-5b5e999b7db48_articlex.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 '成功请求到数据';
}
}
登录后复制

三、 测试效果如图:

1)首先不带access_token请求, test()方法:

647632294-5b5e95d74a9b2_articlex.png

结果出现一个401未验证通过的状态

2)然后请求一个错误的access_token, test()方法

1015616854-5b5e9602a2730_articlex.png
同样是一个401的状态,但此时,如图

1950601440-5b5e961fd45c9_articlex.png

有信息返回给我们

3) 最后,使用一个正确的access_token, test()方法

2209170030-5b5e966630e56_articlex.png

所以,基于第1种情况和第2种情况,你应该自定一个token未验证成功的方法,如图:

3764678513-5b5e9741923f9_articlex.png

3429626366-5b5e975a61713_articlex.png

819359002-5b5e9773be43d_articlex.png

3305399504-5b5e978892c27_articlex.png

完结。

相关文章推荐:

php实现用于验证所有类型的信用卡类

thinkphp验证码的实现(form、ajax实现验证)_php实例

以上就是ThinkPHP5中使用 Auth2进行验证的过程分析的详细内容,更多请关注php中文网其它相关文章!

相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学