yii2.0 高级版,restful api使用和认证

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规则 每添加一个方法必须在此注册(除非配置了通用配置

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

'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,具体格式自己调试 主要有正常返回数据,手动抛出异常、系统异常

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

'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里可以看到,不需要时继承后直接返回空就可以。

1

2

3

4

5

6

7

8

9

10

11

<?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认证

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

    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' => [],

         ];

 

        // 这个是跨域配置

        $behaviors['corsFilter'] = [

            'class' => \yii\filters\Cors::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'] =  \yii\web\Response::FORMAT_JSON;

        return $behaviors;

    }

认证关键部分:登陆的时候就可以获取token存起来,下行请求带上。
①
main.php 设置components,指定认证类
'user' => [
'identityClass' => 'common\models\User',
//            'identityClass' => 'pro\modules\log\models\TypeModel',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
②
主要就是重写模型User里的findIdentityByAccessToken方法(之前就卡在这里),当然还有一些其他的一些方法。
这里面其实是根据传过来的token做验证。最主要的就是要返回当前对象出去,如果token
无效可以返回空数组。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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配置的方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

class ExceptionController extends \yii\web\Controller

{

  

//错误处理

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' => 'yii\web\Response',

'format' => \yii\web\Response::FORMAT_JSON,

'data' => [

'code' => $code,

'info' => $exception->getMessage()

],

]);

}

}

7、日志设置 main 下面的components里log。可以设置多个。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

'log' => [

'traceLevel' => YII_DEBUG ? 3 : 0,

'flushInterval' => 1,

'targets' => [

'frontend' => [

'class' => 'yii\log\FileTarget',

'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]\n";

},

],

'admin' => [

'class' => 'yii\log\FileTarget',

'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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值