在配置中如有問題:加Q405420415,有問必答。
一. yii2.0幾種授權的介紹
RESTful APIs 通常是無狀態的, 也就意味着不應使用 sessions 或 cookies, 因此每個請求應附帶某種授權憑證,因爲用戶授權狀態可能沒通過 sessions 或 cookies 維護, 常用的做法是每個請求都發送一個祕密的 access token 來認證用戶, 由於 access token 可以唯一識別和認證用戶, API 請求應通過 HTTPS 來防止 man-in-the-middle(MitM)中間人攻擊。
/*以上摘自YII中國官方文檔*/
下面有幾種方式(稍微自己整理下,感覺看起來更容易理解點):
- HttpBasicAuth:在請求的頭添加Authorization(即:Authorization: "Basic 用戶名和密碼的base64加密字符串" )
- HttpBearerAuth:在請求的頭添加Authorization(即:Authorization: "Bearer access-token" )
- QueryParamAuth:在URL結尾添加GET參數access-token(即:
https://demo.com/users?access-token=xxxxxxxx
)
二. 詳細的配置
① 重寫common/user/models的findIdentityByAccessToken方法
/**
* {@inheritdoc}
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
② 添加控制層登錄的相關代碼(能夠保存到數據庫中,如果LoginForm沒有請重新用命裏安裝下,這些文件都是安裝完後自帶的,然後複製到api/models這個目錄來,其中user表是利用yii-admin 擴展組件裏面migrate生成的,前面博客有介紹其安裝流程)
<?php
namespace api\controllers;
use api\models\LoginForm;
use yii\rest\ActiveController;
use Yii;
/**
* User controller
*/
class UserController extends ActiveController
{
public $modelClass = 'common\models\User';
/**
* 登陸
* @return array
* @throws \yii\base\Exception
* @throws \yii\base\InvalidConfigException
*/
public function actionLogin()
{
$model = new LoginForm();
if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->login()) {
return [
'access_token' => $model->login(),
];
} else {
return $model->getFirstErrors();
}
}
}
③ 重寫api/models/LoginForm.php的login方法
/**
* Logs in a user using the provided username and password.
*
* @return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
$access_token = $this->_user->generateAccessToken();
$this->_user->save();
return $access_token;
} else {
return false;
}
}
三. postman測試API接口,我這邊多創建了Article控制器,來測試(我先上代碼,有幾個注意事項我在代碼中註釋)
<?php
namespace api\controllers;
use yii\rest\ActiveController;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use Yii;
class ArticleController extends ActiveController
{
public $modelClass = '';
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
//這邊選擇你要開啓的驗證方式
'authMethods' => [
HttpBasicAuth::className(),
HttpBearerAuth::className(),
QueryParamAuth::className(),
],
];
return $behaviors;
}
/**
* GET 返回文章的內容
* @return array
*/
public function actionGetArticleInfo()
{
return ['title' => 'title', 'content' => 'content'];
}
}
① 登陸API接口
②獲取文章信息(我這邊用HttpBearerAuth,其餘大家自己摸索下,都差不多,選擇自己想要的。還有個注意點記得在配置文件那邊把Artilce這個控制器加進去,不然會報404找不到,這個在上個RESTful教程一有講解到)
/*這圖是我故意沒有在header添加驗證信息,會報的錯誤*/
/*這是成功的*/