Wou*_*den 9 authentication api rest yii2 bearer-token
我做了一个Yii2 REST API.使用API,您可以获得汽车列表.现在我想使用承载身份验证来保护API.但我不知道它是如何工作的.
首先.我在控制器的behavior方法中设置了authenticator.
public function behaviors(){
return [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
],
'authenticator' => [
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBearerAuth::className(),
],
]
];
}
Run Code Online (Sandbox Code Playgroud)
这很好用.如果我转到URL,我将收到"未经授权"的消息.
在我的wordpress插件中,我已经创建了一个函数来使用API并使用身份验证密钥设置标头.
function getJSON($template_url) {
$authorization = "Authorization: Bearer " . get_option("auth_key");
// Create curl resource
$ch = curl_init();
// Set URL
curl_setopt($ch, CURLOPT_URL, $template_url);
// Return transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization));
// $output contains output as a string
$output = curl_exec($ch);
// Close curl resource
curl_close($ch);
return json_decode($output, true);
}
Run Code Online (Sandbox Code Playgroud)
但现在我的问题是.如果此密钥有效,我该如何检查API并给我回复.我想在de数据库中搜索密钥,如果它存在,它也应该给我同一行中的id或电子邮件.
我不知道该怎么做.
soj*_*oju 10
\yii\filters\auth\HttpBearerAuth::authenticate()只需致电\yii\web\User::loginByAccessToken():
$class = $this->identityClass;
$identity = $class::findIdentityByAccessToken($token, $type);
Run Code Online (Sandbox Code Playgroud)
所以你只需要findIdentityByAccessToken()在你的用户身份类中实现,例如:
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['auth_key' => $token]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7171 次 |
| 最近记录: |