您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

聊聊TP在app接口开发过程中的安全验证问题

2025/8/3 17:43:41发布25次查看
下面thinkphp框架教程栏目将给大家介绍关于thinkphp在app接口开发过程中的通讯安全认证问题,希望对需要的朋友有所帮助!
对于我们写好的接口,如果不经过安全认证就可以直接访问的话,则将对我们网站产生非常大的安全隐患,一些hack可能直接用你的接口去操作数据库,后果无法估量。
那么如何才能进行有效的安全验证呢?
这里采用了微信开发中的access_token机制,让app前端开发工程师通过提交appid和appsecert来获取token,服务器端对token缓存7200秒,客户端如果每次都直接请求token则token每次都会重置;
所以推荐客户端也一样进行缓存,客户端可以通过判断本地token是否存在,如果存在则直接用token做参数去访问我们的api,服务端判断token的有效性并给予相应的返回,客户端缓存的token如果失效了,就直接再请求获取token,思路大概就是这样,下面提供了完整的参考代码,如果有更好的方法,也可留言
<?phpnamespace home\controller;use think\controller;class indexcontroller extends controller { public $appid = 'dmm888'; public $appsecret = 'http://cnblogs.com/dmm888'; public function index(){ $this->show('<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} body{ background: #fff; font-family: "微软雅黑"; color: #333;font-size:24px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.8em; font-size: 36px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p>欢迎使用 <b>thinkphp</b>!</p><br/>[ 您现在访问的是home模块的index控制器 ]</div><script type="text/javascript" src="http://tajs.qq.com/stats?sid=9347272" charset="utf-8"></script>','utf-8'); } public function test(){ if(!isset($_get['token'])){ $this->apireturn(4001,'invalid token'); }else if(!s($_get['token'])){ $this->apireturn(4001,'invalid token'); } $data = array( 'id'=>2, 'username'=>'明之暗夜', 'info'=>array('age'=>24,'address'=>'学府路','url'=>'http://cnblogs.com/dmm888') ); if($data){ $this->apireturn(200,'读取用户信息成功',$data,xml); } } public function gettoken(){ $ori_str = s($this->appid.'_'.$this->appsecret); //这里appid和appsecret我写固定了,实际是通过客户端获取 所以这里我们可以做很多 比如判断appid和appsecret有效性等 if($ori_str){ //重新获取就把以前的token删除 s($ori_str,null); } //这里是token产生的机制 您也可以自己定义 $nonce = $this->createnoncestr(32); $tmparr = array($nonce,$this->appid,$this->appsecret); sort($tmparr, sort_string); $tmpstr = implode( $tmparr ); $tmpstr = sha1( $tmpstr ); // echo $tmpstr; //这里做了缓存 'a'=>b 和'b'=>a格式的缓存 s($this->appid.'_'.$this->appsecret,$tmpstr,7200); s($tmpstr,$this->appid.'_'.$this->appsecret,7200); } /** * 作用:产生随机字符串,不长于32位 */ function createnoncestr( $length = 32 ) { $chars = "abcdefghijklmnopqrstuvwxyz0123456789"; $str =""; for ( $i = 0; $i < $length; $i++ ) { $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1); } return $str; } }
具体怎么验证我就不用写了吧,这样我们只需把appid和appsecret给app前端开发者 并告诉他怎么用就可以了 token就是唯一令牌 只有token有效才可以向下执行 从而安全性可以得到一定保证 。
推荐学习:《最新的10个thinkphp视频教程》
以上就是聊聊tp在app接口开发过程中的安全验证问题的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product