设为首页 加入收藏

TOP

yii2.0 高级版 restful api使用和认证(一)
2019-08-23 00:42:34 】 浏览:113
Tags:yii2.0 高级 restful api 使用 认证
 
1、复制任意个目录(backend)为api
2、打开api下的main.php 修改 id=>app-api,'controllerNamespace' => 'api\controllers', 'identityClass' => 'app\models\User'(用户认证,暂无用),'errorAction' => 'exception/errorr',(修改错误处)
注意:每一个方法都需要在extraPatterns里配置,也可以设置统一匹配的模式:'<action:\w+-?\w+>' => '<action>' 该模式将匹配所有有效请求
①在components里添加URL规则 每添加一个方法必须在此注册( 除非配置了通用配置
'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,//严格模式
    'showScriptName' => false,
    'suffix' => '.html', // 后缀,访问方法的后缀
    'rules' => [
        [
            'class' => 'yii\rest\UrlRule',
            //'pluralize' => false,    //设置为false 就可以去掉复数形式了,不然访问控制器得加上s
            'controller' => 'api',     //也可以设置多个 ['api/hello','log/test']  api,log表示模块
            'extraPatterns' => [    //可以把这一项配置去掉,新增最后两个通用配置:('<controller:\w+-?\w+>/<action:\w+-?\w+>' => '<controller>/<action>','<modules:\w+-?\w+>/<controller:\w+-?\w+>/<action:\w+-?\w+>' => '<modules>/<controller>/<action>',)。当然也可以配置一个通用action,       就是把具体的方法指向改为通用(  '<action:\w+-?\w+>' => '<action>')
                'GET index' => 'index',
                'POST,GET test' => 'test'
                //  '<action:\w+-?\w+>' => '<action>' //通用方法配置

            ],
//        //'<controller:\w+-?\w+>/<action:\w+-?\w+>' => '<controller>/<action>',
//        //'<modules:\w+-?\w+>/<controller:\w+-?\w+>/<action:\w+-?\w+>' => '<modules>/<controller>/<action>',
        ],
    ],
 ]

②自定义返回200,具体格式自己调试 主要有正常返回数据,手动抛出异常、系统异常

'response' => [
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
if (isset($response->data['message'])){
$response->data = [
// 'success' => $response->isSuccessful,
'code' => isset($response->data['code'])?$response->data['code']:500,
// 'message' => $response->statusText,
'info' => isset($response->data['message'])?$response->data['message']:'app error',
];
 
}
$response->statusCode = 200;
},
],
3、打开common下的bootstrap.php 添加 Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
4、创建控制器继承yii\rest\ActiveController。默认会有一些方法,在父类actions里可以看到, 不需要时继承后直接返回空就可以
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
    public function actions()
    {
        return []; // TODO: Change the autogenerated stub
    }
    public $modelClass = 'app\models\User'; //必须制定模型,控制器才知道去哪里获取处理数据
}
5、定义一些行为,自动返回json、跨域等。 设置认证,这里主要使用HttpBearerAuth认证
    public function behaviors()
    {
        $behaviors = parent::behaviors();
         $behaviors['authenticator'] = [
//         'class' => yii\filters\auth\CompositeAuth::className(),
         'class' => \yii\filters\auth\HttpBearerAuth::className(),
//         'authMethods' =>
//         [
//         # 下面是三种验证access_token方式
//             yii\filters\auth\HttpBasicAuth::className(),
//             yii\filters\auth\HttpBearerAuth::className(),
//         //这是GET参数验证的方式 # http://10.10.10.252:600/user/index/index?access-token=xxxxxxxxxxxxxxxxxxxx
//             yii\filters\auth\QueryParamAuth::className(),
//         ],
         // 写在optional里的方法不需要token验证
         'optional' => [],
         ];

        //
首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇phpmock测试 下一篇yii2.0 URL美化

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目