zoukankan      html  css  js  c++  java
  • yii2.0 高级版 restful api使用和认证

     
    1、复制任意个目录(backend)为api
    2、打开api下的main.php 修改 id=>app-api,'controllerNamespace' => 'apicontrollers', 'identityClass' => 'appmodelsUser'(用户认证,暂无用),'errorAction' => 'exception/errorr',(修改错误处)
    注意:每一个方法都需要在extraPatterns里配置,也可以设置统一匹配的模式:'<action:w+-?w+>' => '<action>' 该模式将匹配所有有效请求
    ①在components里添加URL规则 每添加一个方法必须在此注册(除非配置了通用配置
    'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,//严格模式
        'showScriptName' => false,
        'suffix' => '.html', // 后缀,访问方法的后缀
        'rules' => [
            [
                'class' => 'yii
    estUrlRule',
                //'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' => 'yiiwebResponse',
    '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 estActiveController。默认会有一些方法,在父类actions里可以看到,不需要时继承后直接返回空就可以
    <?php
    namespace appcontrollers;
    use yii
    estActiveController;
    class UserController extends ActiveController
    {
        public function actions()
        {
            return []; // TODO: Change the autogenerated stub
        }
        public $modelClass = 'appmodelsUser'; //必须制定模型,控制器才知道去哪里获取处理数据
    }
    5、定义一些行为,自动返回json、跨域等。设置认证,这里主要使用HttpBearerAuth认证
        public function behaviors()
        {
            $behaviors = parent::behaviors();
             $behaviors['authenticator'] = [
    //         'class' => yiifiltersauthCompositeAuth::className(),
             'class' => yiifiltersauthHttpBearerAuth::className(),
    //         'authMethods' =>
    //         [
    //         # 下面是三种验证access_token方式
    //             yiifiltersauthHttpBasicAuth::className(),
    //             yiifiltersauthHttpBearerAuth::className(),
    //         //这是GET参数验证的方式 # http://10.10.10.252:600/user/index/index?access-token=xxxxxxxxxxxxxxxxxxxx
    //             yiifiltersauthQueryParamAuth::className(),
    //         ],
             // 写在optional里的方法不需要token验证
             'optional' => [],
             ];
    
            // 这个是跨域配置
            $behaviors['corsFilter'] = [
                'class' => yiifiltersCors::className(),
                'cors' => [
                    'Origin' => ['*'],
                    'Access-Control-Request-Method' => ['POST', 'GET', 'DEL'],
                    'Access-Control-Request-Headers' => ['Origin', 'X-Requested-With', 'Content-Type', 'Accept'],
                    'Access-Control-Allow-Origin' => ['*'],
                    'Access-Control-Allow-Credentials' => true,
                    'Access-Control-Max-Age' => 3600,
                    'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
                ],
            ];
            //定义返回格式是:JSON
            $behaviors['contentNegotiator']['formats']['text/html'] =  yiiwebResponse::FORMAT_JSON;
            return $behaviors;
        }
    认证关键部分:登陆的时候就可以获取token存起来,下行请求带上。

    main.php 设置components,指定认证类
    'user' => [
    'identityClass' => 'commonmodelsUser',
    // 'identityClass' => 'promoduleslogmodelsTypeModel',
    'enableAutoLogin' => true,
    'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
    ],

    主要就是重写模型User里的findIdentityByAccessToken方法(之前就卡在这里),当然还有一些其他的一些方法。
    这里面其实是根据传过来的token做验证。最主要的就是要返回当前对象出去,如果token
    无效可以返回空数组。
       public static function findIdentityByAccessToken($token, $type = null)
        {
       //return static::findOne(['access_token' => $token]);//查数据库
            $userId = Yii::$app->redis->get($token);
            if ($userId){
                $userData = Yii::$app->redis->hget($userId);
                $model = new User();
    
                if (empty($userData)) return [];
    
                $userData = json_decode($userData,true);
                $model->attributes = $userData;//把查询到的用户信息填入属性
                return $model;
            }
    
            return [];
        }
    请求时带上token
    设置请求头
    key: Authorization
    value: Bearer token
    注意:Bearer token 这两者之间必须有一个空格
    例如:
    curl -v -H 'Authorization: Bearer ere2123' http://192.168.1.157/advanced/pro/web/log/test/msg.html
    6、定义自己的错误,就是errorAction配置的方法
    class ExceptionController extends yiiwebController
    {
     
    //错误处理
    public function actionError()
    {
    $exception = Yii::$app->errorHandler->exception;
    $code = $exception->statusCode ? $exception->statusCode : $exception->getCode();
    //CommonController::response( $code ? $code : 400,$exception->getMessage());
     
    return Yii::createObject([
    'class' => 'yiiwebResponse',
    'format' => yiiwebResponse::FORMAT_JSON,
    'data' => [
    'code' => $code,
    'info' => $exception->getMessage()
    ],
    ]);
    }
    }
    7、日志设置 main 下面的components里log。可以设置多个。
    'log' => [
    'traceLevel' => YII_DEBUG ? 3 : 0,
    'flushInterval' => 1,
    'targets' => [
    'frontend' => [
    'class' => 'yiilogFileTarget',
    'levels' => ['error', 'warning'],
    'exportInterval' => 1,
    'logFile' => '../logs/frontend/'.date('Ymd').'.log',
    'logVars' => ['_POST','_GET'], //捕获请求参数
    'fileMode' => 0775, //设置日志文件权限
    'rotateByCopy' => false, //是否以复制的方式rotate
    'prefix' => function() { //日志格式自定义 回调方法
    if (Yii::$app === null) {
    return '';
    }
    $controller = Yii::$app->controller->id;
    $action = Yii::$app->controller->action->id;
    return "[$controller-$action]
    ";
    },
    ],
    'admin' => [
    'class' => 'yiilogFileTarget',
    'levels' => ['error', 'warning','info'],
    'exportInterval' => 1,
    'logFile' => '../logs/admin/'.date('Ymd').'.log',
    'logVars' => ['_POST','_GET'], //捕获请求参数
    'fileMode' => 0775, //设置日志文件权限
    'rotateByCopy' => false, //是否以复制的方式rotate
    ],
    ],
    ],
    在控制器里主要通过设置属性来开启关闭
    Yii::$app->log->targets['frontend']->enabled = true;
    Yii::$app->log->targets['admin']->enabled = true;
     
    手动写入日志 : Yii::warning($result,'frontend');
     
    8、多数据库配置 在components 里添加配置 默认的id 为db
    ①添加三个配置
    $db = require(__DIR__ . '/db.php');
    'normal_ios' => $db['normal_ios'],
    'normal_android' => $db['normal_android'],
    'normal_web' => $db['normal_web'],
    ②使用的时候指定一个
    Yii::$app->normal_ios
    Yii::$app->normal_android
    Yii::$app->normal_web
    $this->find()->where($where)->one(Yii::$app->normal_ios);
    Yii::$app->normal_ios->createCommand() ->update($tab,$date,$where)->execute();
    ③在视图里使用model模型的时候需要注意 重写getDb方法,不然取字段生成表单的时候会报错找不到哪个db
    //防止构建表单是出错
    public static function getDb()
    {
    return Yii::$app->normal_web
    }
     
    9、设置session
    'session' => [
    'cookieParams' => ['lifetime' => 3600*24],//有效时间
    ],
     
    10、nginx配置URL支持pathinfo
    location ~ .php$ { #去掉$
    root E:/phpStudy/WWW/tp/public/;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+.php)(.*)$; #增加这一句
    fastcgi_param PATH_INFO $fastcgi_path_info; #增加这一句
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    }
  • 相关阅读:
    【OpenGL】Shader实例分析(七)- 雪花飘落效果
    BZOJ 1091([SCOI2003]分割多边形-分割直线)
    Protocol buffer序列化及其在微信蓝牙协议中的应用
    运行计划中cost计算方法
    jquery全局变量---同步请求设置
    Java split字符串中包含.的情况
    jQuery获取、设置title的值
    jQuery获取URL中所带参数的办法
    在Eclipse中提交SVN项目的时候注意提交项目信息
    马丁 福勒 Martin Fowler 关于依赖注入和反转控制的区别
  • 原文地址:https://www.cnblogs.com/fwqblogs/p/10132792.html
Copyright © 2011-2022 走看看