【发布时间】:2016-06-13 17:20:43
【问题描述】:
我制作了一个 Yii2 REST API。使用 API,您可以获得汽车列表。现在我想使用 Bearer Authentication 来保护 API。但我不知道它是如何工作的。
首先。我在控制器的行为方法中设置了身份验证器。
public function behaviors(){
return [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
],
'authenticator' => [
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBearerAuth::className(),
],
]
];
}
这很好用。如果我转到 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);
}
但现在我的问题是。如果此密钥有效,我如何签入 API 并给我响应。我想在 de 数据库中搜索键,如果它存在,它还应该给我同一行中的 id 或电子邮件。
我不知道该怎么做。
【问题讨论】:
-
那么每个客户都应该有自己的accesstoken?你想使用 oauth2 吗?
标签: api rest authentication yii2 bearer-token