身份校验
在本小节中我们将会设置身份校验模型。
准备
重复创建一个REST服务器小节中准备和如何做的所有步骤。
如何做…
- 修改
@app/controllers/FilmController:
<?phpnamespace app\controllers;use app\models\User;use Yii;use yii\helpers\ArrayHelper;use yii\rest\ActiveController;use yii\filters\auth\HttpBasicAuth;class FilmController extends ActiveController{public $modelClass = 'app\models\Film';public function behaviors(){return ArrayHelper::merge(parent::behaviors(),['authenticator' => ['authMethods' => ['basicAuth' => ['class' =>HttpBasicAuth::className(),'auth' => function ($username,$password) {$user =User::findByUsername($username);if ($user !== null && $user->validatePassword($password)){return $user;}return null;},]]]]);}}
在浏览器中打开http://yii-book.app/films,确保我们配置了HTTP基本身份验证:

尝试身份验证。在控制台中运行如下命令:
curl -i -H "Accept:application/json" "http://yii-book.app/films"
你将会得到如下结果:
HTTP/1.1 401 UnauthorizedDate: Thu, 24 Sep 2015 01:01:24 GMTServer: ApacheX-Powered-By: PHP/5.5.23Www-Authenticate: Basic realm="api"Content-Length: 149Content-Type: application/json; charset=UTF-8{"name":"Unauthorized","message":"You are requesting with an invalid credential.","code":0,"status":401,"type":"yii\\web\\UnauthorizedHttpException"}
- 现在尝试使用
cURL进行auth:
curl -i -H "Accept:application/json" -u admin:admin "http://yii-book.app/films"
- 你将会得到类似如下结果:
HTTP/1.1 200 OKDate: Thu, 24 Sep 2015 01:01:40 GMTServer: ApacheX-Powered-By: PHP/5.5.23Set-Cookie: PHPSESSID=8b3726040bf8850ebd07209090333103; path=/;HttpOnlyExpires: Thu, 19 Nov 1981 08:52:00 GMTCache-Control: no-store, no-cache, must-revalidate,post-check=0, pre-check=0Pragma: no-cacheX-Pagination-Total-Count: 5X-Pagination-Page-Count: 1X-Pagination-Current-Page: 1X-Pagination-Per-Page: 20Link: <http://yii-book.app/films?page=1>; rel=selfContent-Length: 301Content-Type: application/json; charset=UTF-8[{"id":1,"title":"Interstellar","release_year":2014},{"id":2,"title":"Harry Potter and the Philosopher'sStone","release_year":2001},{"id":3,"title":"Back to theFuture","release_year":1985},{"id":4,"title":"BladeRunner","release_year":1982},{"id":5,"title":"Dallas BuyersClub","release_year":2013}]
工作原理…
我们将authenticator行为添加到了HttpBasicAuth类中,所以我们将可以通过登录名和密码进行身份校验。你可以实现官方文档中RESTful web服务部分的任意身份校验方法。
更多…
其它发送access token的方法:
- HTTP基础验证
- 查询参数
- OAuth
Yii支持所有这些身份校验方法。
参考
欲了解更多信息,参考http://www.yiiframework.com/doc-2.0/guide-rest-rate-limiting.html。
