我无法在我的应用程序中找到验证API用户的方法。我开始构建一个用户可以通过Web访问和验证的系统,但需求已经改变,我需要实现一些可以使用POST API调用以RESTful方式提供的其他操作。
我创建了一个扩展CBehaviour
的类,并强制重定向到所有未经身份验证的用户(found on the yii framework forum here)的登录页面。问题是所有API调用都强制通过相同的逻辑,任何POST请求只是将HTML吐出到登录页面。
class ApplicationBehavior extends CBehavior {
private $_owner;
public function events() {
return array(
'onBeginRequest' => 'forceGuestLogin',
);
}
public function forceGuestLogin() {
$owner = $this->getOwner();
if ($owner->user->getIsGuest())
$owner->catchAllRequest = array("site/login");
}
}
如何将API用户的身份验证与Web用户分开?
答案 0 :(得分:3)
我会在Yii中创建REST API时遵循此guide。修改config urlManager条目后,所有API请求都将使用APIController。然后,您可以将以下代码放在APIController的beforeAction中,如果用户是访客,则不返回任何内容(或错误消息)
protected function beforeAction($event) {
if (Yii::app()->user->isGuest) {
echo "Invalid credentials";
Yii::app()->end();
}
}
注意:上面的代码适合我的目的,因为所有REST请求都是通过同一个浏览器发送的。 (已登录并具有登录cookie)
如果使用放置在protected/controllers
中的新基本控制器替换该行为以强制登录,则它仅适用于需要登录而不是APIController的页面。以下是我的一个例子:
//Make sure all Controllers which require a login inherit from this
class ControllerLoginRequired extends CController {
public function runAction($action) {
if (Yii::app()->user->isGuest && 'site' != $this->route) {
Yii::app()->user->returnUrl = $this->route;
parent::redirect(array('site/login'));
} else {
parent::runAction($action);
}
}
}
所有解释的内容都适用于通过用户登录Yii的同一浏览器的REST请求。如果您需要将REST服务暴露给不是登录到Yii的浏览器的消费者,我相信您必须提出自定义身份验证/令牌方案。