【问题标题】:Allowing users to access API with CakePHP允许用户使用 CakePHP 访问 API
【发布时间】:2012-07-10 23:41:57
【问题描述】:

我正在构建一个 CakePHP 应用程序并且我有一个 API 控制器。这包含一些在站点中很常见的方法,我将它们与 jQuery AJAX 调用一起使用来做某些事情。我最近使用 Auth 组件实现了用户注册,但现在每当我在未登录的情况下尝试访问 API 时,我都会被重定向到登录页面。

这是我的AppController 代码:

class AppController extends Controller {   
    public $components = array('Session', 'Auth' => array(
        'loginRedirect' => array('controller' => 'users', 'action' => 'images'),
        'logoutRedirect' => array('controller' => 'pages', 'action' => 'home')
    ));

    public function beforeRender() {
        $this->set('loggedIn', $this->Auth->loggedIn());
        $this->set('username', $this->Auth->user('username'));
    }

    public function beforeFilter() {
        $this->Auth->allow('home', 'register', 'login');
    }
}

我知道我可以使用 $this->Auth->allow() 方法在我的 API 控制器中允许某些方法,但是有没有办法让它在控制器范围内?例如,我可以在我的 API 控制器中放入一些东西,以便未登录的用户也可以访问它的方法吗?我宁愿不要将每个操作的方法名称放在允许列表中,因为大约有 30 个。

谢谢。

【问题讨论】:

    标签: php api cakephp authentication controllers


    【解决方案1】:

    把这个放在 ApiController 中:

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow(); //pass no arguments to allow all
    }
    

    【讨论】:

    • 这仅适用于 CakePHP 2.1+,如果您使用的是 CakePHP 2.0,请确保使用 $this->Auth->allow('*');
    猜你喜欢
    • 2019-07-07
    • 1970-01-01
    • 2021-01-11
    • 2019-06-29
    • 2017-07-28
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多