“Yii2”的版本间的差异
跳到导航
跳到搜索
(未显示同一用户的1个中间版本) | |||
第1行: | 第1行: | ||
+ | == 认证方式配置 == | ||
+ | 参考教程: https://www.yiichina.com/tutorial/812 | ||
+ | |||
+ | <nowiki> | ||
+ | public function behaviors() | ||
+ | { | ||
+ | $behaviors = parent::behaviors(); | ||
+ | $behaviors['authenticator'] = [ | ||
+ | //auth method 1 | ||
+ | //'class' => HttpBasicAuth::className(), | ||
+ | //auth method 2 | ||
+ | 'class' => HttpBearerAuth::className(), | ||
+ | //auth method 3 | ||
+ | //'class' => QueryParamAuth::className(), | ||
+ | //auth method 4 复合认证 | ||
+ | 'class' => CompositeAuth::className(), | ||
+ | 'authMethods' => [ | ||
+ | HttpBasicAuth::className(), | ||
+ | HttpBearerAuth::className(), | ||
+ | QueryParamAuth::className(), | ||
+ | ], | ||
+ | 'optional'=>['login'],// 不用认证的action, 配置的是action id。 | ||
+ | ]; | ||
+ | return $behaviors; | ||
+ | } | ||
+ | </nowiki> | ||
+ | |||
+ | identityClass继承IdentityInterface,实现findIdentityByAccessToken等方法 | ||
== yii2自定义异常页面 == | == yii2自定义异常页面 == |
2019年8月23日 (五) 11:36的最新版本
认证方式配置
参考教程: https://www.yiichina.com/tutorial/812
public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ //auth method 1 //'class' => HttpBasicAuth::className(), //auth method 2 'class' => HttpBearerAuth::className(), //auth method 3 //'class' => QueryParamAuth::className(), //auth method 4 复合认证 'class' => CompositeAuth::className(), 'authMethods' => [ HttpBasicAuth::className(), HttpBearerAuth::className(), QueryParamAuth::className(), ], 'optional'=>['login'],// 不用认证的action, 配置的是action id。 ]; return $behaviors; }
identityClass继承IdentityInterface,实现findIdentityByAccessToken等方法
yii2自定义异常页面
框架中异常是由yii\web\ErrorHandler类处理,所以继承他并重写(renderException)就好了。
1. 创建类app\components\ErrorHandler
+<?php +/** + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ + */ + +namespace app\components; + +use Yii; +use yii\base\ErrorException; +use yii\base\Exception; +use yii\web\ErrorHandler as BaseErrorHandler; +use yii\helpers\VarDumper; +use \yii\web\Response; + +class ErrorHandler extends BaseErrorHandler +{ + protected function renderException($exception) + { + if ($exception instanceof \yii\web\UnauthorizedHttpException) { + $response = new Response(); + $response->format = Response::FORMAT_JSON; + $response->data = ["status"=>1001,"msg"=>"未登录"]; + $response->send(); + return; + }else{ + return parent::renderException($exception); + } + } +}
2. 修改config/main.php
'components'=>[ + 'errorHandler'=>[ + 'errorAction' => 'site/error', + 'class' => 'app\components\ErrorHandler', + ], ],
当抛出yii\web\UnauthorizedHttpException异常时,就会返回上面定义的{"status": 1001,"msg": "未登录"}
了