我制作了Yii2 REST API。使用API,您可以获取汽车列表。现在我想使用承载认证来保护API。但我不知道它是如何工作的。Yii2 Rest API承载验证
首先。我在我的控制器的行为方法中设置了身份验证器。
public function behaviors(){
return [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
],
'authenticator' => [
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBearerAuth::className(),
],
]
];
}
这工作得很好。如果我转到网址,我会收到'未经授权'的信息。
在我的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);
}
但现在我的问题是。如果此密钥有效并且给我回复,我如何检查API?我想搜索数据库中的密钥,如果它存在,它也应该给我在同一行中的id或电子邮件。
我不知道如何做到这一点。
那么每个客户都应该有他自己的accesstoken?你想使用oauth2? –