身份校验

在本小节中我们将会设置身份校验模型。

准备

重复创建一个REST服务器小节中准备如何做的所有步骤。

如何做…

  1. 修改@app/controllers/FilmController
  1. <?php
  2. namespace app\controllers;
  3. use app\models\User;
  4. use Yii;
  5. use yii\helpers\ArrayHelper;
  6. use yii\rest\ActiveController;
  7. use yii\filters\auth\HttpBasicAuth;
  8. class FilmController extends ActiveController
  9. {
  10. public $modelClass = 'app\models\Film';
  11. public function behaviors()
  12. {
  13. return ArrayHelper::merge(parent::behaviors(),[
  14. 'authenticator' => [
  15. 'authMethods' => [
  16. 'basicAuth' => [
  17. 'class' =>HttpBasicAuth::className(),
  18. 'auth' => function ($username,$password) {
  19. $user =User::findByUsername($username);
  20. if ($user !== null && $user->validatePassword($password)){
  21. return $user;
  22. }
  23. return null;
  24. },
  25. ]
  26. ]
  27. ]
  28. ]);
  29. }
  30. }

在浏览器中打开http://yii-book.app/films,确保我们配置了HTTP基本身份验证:

身份校验 - 图1

尝试身份验证。在控制台中运行如下命令:

  1. curl -i -H "Accept:application/json" "http://yii-book.app/films"

你将会得到如下结果:

  1. HTTP/1.1 401 Unauthorized
  2. Date: Thu, 24 Sep 2015 01:01:24 GMT
  3. Server: Apache
  4. X-Powered-By: PHP/5.5.23
  5. Www-Authenticate: Basic realm="api"
  6. Content-Length: 149
  7. Content-Type: application/json; charset=UTF-8
  8. {"name":"Unauthorized","message":"You are requesting with an invalid credential.","code":0,"status":401,"type":"yii\\web\\UnauthorizedHttp
  9. Exception"}
  1. 现在尝试使用cURL进行auth
  1. curl -i -H "Accept:application/json" -u admin:admin "http://yii-book.app/films"
  1. 你将会得到类似如下结果:
  1. HTTP/1.1 200 OK
  2. Date: Thu, 24 Sep 2015 01:01:40 GMT
  3. Server: Apache
  4. X-Powered-By: PHP/5.5.23
  5. Set-Cookie: PHPSESSID=8b3726040bf8850ebd07209090333103; path=/;
  6. HttpOnly
  7. Expires: Thu, 19 Nov 1981 08:52:00 GMT
  8. Cache-Control: no-store, no-cache, must-revalidate,
  9. post-check=0, pre-check=0
  10. Pragma: no-cache
  11. X-Pagination-Total-Count: 5
  12. X-Pagination-Page-Count: 1
  13. X-Pagination-Current-Page: 1
  14. X-Pagination-Per-Page: 20
  15. Link: <http://yii-book.app/films?page=1>; rel=self
  16. Content-Length: 301
  17. Content-Type: application/json; charset=UTF-8
  18. [{"id":1,"title":"Interstellar","release_year":2014},{"id":2,"ti
  19. tle":"Harry Potter and the Philosopher's
  20. Stone","release_year":2001},{"id":3,"title":"Back to the
  21. Future","release_year":1985},{"id":4,"title":"Blade
  22. Runner","release_year":1982},{"id":5,"title":"Dallas Buyers
  23. Club","release_year":2013}]

工作原理…

我们将authenticator行为添加到了HttpBasicAuth类中,所以我们将可以通过登录名和密码进行身份校验。你可以实现官方文档中RESTful web服务部分的任意身份校验方法。

更多…

其它发送access token的方法:

  • HTTP基础验证
  • 查询参数
  • OAuth

Yii支持所有这些身份校验方法。

参考

欲了解更多信息,参考http://www.yiiframework.com/doc-2.0/guide-rest-rate-limiting.html