Skip to main content

验证

HttpBasicAuth:在请求的头添加Authorization(即:Authorization: "Basic 用户名和密码的base64加密字符串" )

HttpBearerAuth:在请求的头添加Authorization(即:Authorization: "Bearer access-token" )

QueryParamAuth:在URL结尾添加GET参数access-token(即: https://demo.com/users?access-token=xxxxxxxx)

如果你想支持上面解释的所有三种认证方法,可以使用 CompositeAuth,如下所示:

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;

public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBasicAuth::className(),
HttpBearerAuth::className(),
QueryParamAuth::className(),
],
];
return $behaviors;
}

HttpHeaderAuth 默认使用了 loginByAccessToken() user 应用程序组件的方法并传递 X-Api-Key 头的值。 此实现用于验证 API 客户端。

$behaviors['basicAuth'] = [
'class' => \yii\filters\auth\HttpHeaderAuth::className(),
];

// 请求的时候HTTP的header加入X-Api-Key 值为access-token的值