CakePHP 2.1 - 作为具有身份验证的 Web 应用程序和 REST 服务 [英] CakePHP 2.1 - As a web application and REST service with Authentication

查看:36
本文介绍了CakePHP 2.1 - 作为具有身份验证的 Web 应用程序和 REST 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个 CakePHP 应用程序,该应用程序目前具有表单身份验证.我还想打开此应用程序以供其他应用程序通过 REST 连接.

I'm currently developing a CakePHP application which currently has form authentication. I would also like to open up this application for other applications to connect to via REST.

我知道 CakePHP 可以使用

I know that CakePHP would be able to do this using the

Router::mapResources() 

Router::parseExtensions() 

但是,我不确定如何使用 Basic 或 Digest HTTP 身份验证来实现这一点.

However, I'm unsure how to get this working with say Basic or Digest HTTP authentication.

我在 AppController.php 中有以下内容

I've got the following in the AppController.php

public $components = array(
    'Session',
    'Auth' => array(
        'authenticate' => array(
            'Form'
        ),
        'loginAction' => array(
            'admin' => false,
            'controller' => 'users',
            'action' => 'login'
        ),
        'loginRedirect' => array(
            'controller' => 'users',
            'action' => 'home'
        )
    )
);

如果对于身份验证字段,例如我在基本"中使用 - 当登录基于 Web 的版本时,我得到一个 HTTP 身份验证框,而不是基于 Web 的表单.

If for the authenticate field, I had in 'Basic' for example - when logging into the web based version, I get an HTTP auth box and not the web based form.

这样做的最佳方法是什么?目前我能想到的唯一方法是创建一个单独的 ApiController 并手动进行身份验证?

What is the best way of doing this? The only way I can think of at the moment is to create a separate ApiController and manually do authentication?

任何建议都会很棒.

更新:

这是我修改后的代码,它给了我正确的行为 - 我很确定应该有更好的方法来做到这一点.

This is my revised code which is giving me the correct behavour - I'm pretty sure that there should be a better way to do this.

class AppController extends Controller {

    public $components = array(
        'Session',
        'RequestHandler',
        'Auth' => array(
            'loginAction' => array(
                'admin' => false,
                'controller' => 'users',
                'action' => 'login'
            ),
            'loginRedirect' => array(
                'controller' => 'users',
                'action' => 'home'
            )
        )
    );

    public $helpers = array('Html', 'Form', 'Session');

    public function beforeFilter() {
        $header = $_SERVER['HTTP_AUTHORIZATION'];
        if($header) {
            $this->Auth->authenticate = array('Basic');
        }
    }

}

推荐答案

public function beforeFilter() {

    // Change the authentication if using REST
    if($this->params['ext'] == 'json') {
        $this->Auth->authenticate = array('Basic');
    }

}

这会检查 JSON 扩展,如果请求包含它 - 然后切换到基本身份验证.

This checks for a JSON extension, if the request contains it - then switch to Basic authentication.

这篇关于CakePHP 2.1 - 作为具有身份验证的 Web 应用程序和 REST 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆