在ZF2控制器中获取请求授权标头

时间:2013-04-11 09:27:49

标签: http zend-framework curl zend-framework2

我正在使用ZF2,出于某种原因,我可以获取我发送的所有标题,除了授权标题 - 就像过滤掉它一样。

我试图在控制器中获取所有标题:

    public function createAction($data) 
    {
        $request  = $this->request;
        print_r ($request->getHeaders());
        exit();

    }

我通过cURL发送请求,如下:

curl -i -H "Accept: test" -H "Authorization: 123456" -H "Content-Type: qwerty" -X POST http://localhost/test

所有标题打印出EXCEPT授权标题。我可以添加任意标题并将其打印出来 - 只是没有'授权'标题...

我也试过get()/ has()作为授权标题,但它不存在。

3 个答案:

答案 0 :(得分:6)

适用于我(ZF2版本2.1.4):

curl -i -H "Accept: test" -H "Authorization: 123456" -X POST http://zf2.localhost

结果:

HTTP/1.1 200 OK
Date: Thu, 11 Apr 2013 09:44:45 GMT
Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
X-Powered-By: PHP/5.4.7
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-ch
Pragma: no-cache
Content-Length: 843
Content-Type: text/html

object(Zend\Http\Headers)#168 (3) {
  ["pluginClassLoader":protected]=>
  NULL
  ["headersKeys":protected]=>
  array(4) {
    [0]=>
    string(9) "useragent"
    [1]=>
    string(4) "host"
    [2]=>
    string(6) "accept"
    [3]=>
    string(13) "authorization"
  }
  ["headers":protected]=>
  array(4) {
    [0]=>
    array(2) {
      ["name"]=>
      string(10) "User-Agent"
      ["line"]=>
      string(23) "User-Agent: curl/7.26.0"
    }
    [1]=>
    array(2) {
      ["name"]=>
      string(4) "Host"
      ["line"]=>
      string(24) "Host: zf2.localhost"
    }
    [2]=>
    array(2) {
      ["name"]=>
      string(6) "Accept"
      ["line"]=>
      string(12) "Accept: test"
    }
    [3]=>
    array(2) {
      ["name"]=>
      string(13) "Authorization"
      ["line"]=>
      string(21) "Authorization: 123456"
    }
  }
}

使用以下代码:

$request  = $this->getRequest();
var_dump($request->getHeaders());

使用以下内容获取值:

$authVal = $request->getHeaders('authorization')->getFieldValue();

希望这会有所帮助:)

答案 1 :(得分:3)

我终于找到了答案:

http://zend-framework-community.634137.n4.nabble.com/HTTP-Digest-authentication-does-not-work-with-PHP-as-CGi-td4658790.html

必须将以下内容添加到项目.htaccess:

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

答案 2 :(得分:0)

希望这能帮助你zf2

  $headers = $request->getHeaders();
  $authorization = $headers->get('Authorization')->getFieldValue();

$ request是Zend\Http\Request;

的对象