检查标头在Restler API框架上的授权

时间:2011-10-19 09:00:13

标签: php api rest

我想扩展Restler以检查是否传递了自定义标头授权的有效值。我在解决问题时遇到了麻烦,我试过了,但没有机会:

class AuthenticateMe implements iAuthenticate() {

function __isAuthenticated() {
    //return isset($_SERVER['HTTP_AUTH_KEY']) && $_SERVER['HTTP_AUTH_KEY']==AuthenticateMe::KEY ? TRUE : FALSE;
    $headers = apache_request_headers();
    foreach ($headers as $header => $value) {
        if($header == "Authorization") {
            return TRUE;
        } else {
            //return FALSE;
            throw new RestException(404);
        }
    }
}
}

2 个答案:

答案 0 :(得分:9)

让我快速修复您的自定义身份验证标题示例

class HeaderAuth implements iAuthenticate{
    function __isAuthenticated(){
        //we are only looking for a custom header called 'Auth'
        //but $_SERVER prepends HTTP_ and makes it all uppercase
        //thats why we need to look for 'HTTP_AUTH' instead
        //also do not use header 'Authorization'. It is not
        //included in PHP's $_SERVER variable
        return isset($_SERVER['HTTP_AUTH']) && $_SERVER['HTTP_AUTH']=='password';
    }
}

我测试了它以确保它有效!

以下是如何使其与授权标头一起使用,它仅适用于apache服务器

 class Authorization implements iAuthenticate{
    function __isAuthenticated(){
        $headers =  apache_request_headers();
        return isset($headers['Authorization']) && $headers['Authorization']=='password';
    }
}

我发现PHP将Authorization标头转换为$_SERVER['PHP_AUTH_DIGEST']$_SERVER['PHP_AUTH_USER']$_SERVER['PHP_AUTH_PW'],具体取决于身份验证请求的类型(摘要或基本),我们可以使用关注.htaccess文件以启用$_SERVER['HTTP_AUTHORIZATION']标题

DirectoryIndex index.php

DirectoryIndex index.php
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^$ index.php [QSA,L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php [QSA,L]
    RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]
</IfModule>

重要的部分是 RewriteRule。* - [env = HTTP_AUTHORIZATION:%{HTTP:授权},最后]

现在我们的例子可以简化为:

class Authorization implements iAuthenticate{
    function __isAuthenticated(){
        return isset($_SERVER['HTTP_AUTHORIZATION']) && $_SERVER['HTTP_AUTHORIZATION']=='password';
    }
}

答案 1 :(得分:2)

标头身份验证

有三种方法可以做到这一点

  1. HTTP基本身份验证
  2. HTTP摘要式身份验证
  3. 使用自定义HTTP标头推送自己的
  4. 您可以从PHP Manual

    了解更多信息

    Restler 1.0有一个Digest Authentication示例。我已修改为使其与Restler 2.0一起使用

    class DigestAuthentication implements iAuthenticate
    {
        public $realm = 'Restricted API';
        public static $user;
        public $restler;
    
    
        public function __isAuthenticated()
        {
            //user => password hardcoded for convenience
            $users = array('admin' => 'mypass', 'guest' => 'guest');
            if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
                header('HTTP/1.1 401 Unauthorized');
                header('WWW-Authenticate: Digest realm="'.$this->realm.'",qop="auth",nonce="'.
                uniqid().'",opaque="'.md5($this->realm).'"');
                throw new RestException(401, 'Digest Authentication Required');
            }
    
            // analyze the PHP_AUTH_DIGEST variable
            if (!($data = DigestAuthentication::http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
            !isset($users[$data['username']]))
            {
                throw new RestException(401, 'Wrong Credentials!');
            }
    
    
            // generate the valid response
            $A1 = md5($data['username'] . ':' . $this->realm . ':' . $users[$data['username']]);
            $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
            $valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
    
            if ($data['response'] != $valid_response)
            {
                throw new RestException(401, 'Wrong Credentials!');
            }
            // ok, valid username & password
            DigestAuthentication::$user=$data['username'];
            return true;
        }
    
        /**
         * Logs user out of the digest authentication by bringing the login dialog again
         * ignore the dialog to logout
         *
         * @url GET /user/login
         * @url GET /user/logout
         */
        public function logout()
        {
            header('HTTP/1.1 401 Unauthorized');
            header('WWW-Authenticate: Digest realm="'.$this->realm.'",qop="auth",nonce="'.
            uniqid().'",opaque="'.md5($this->realm).'"');
            die('Digest Authorisation Required');
        }
    
    
        // function to parse the http auth header
        private function http_digest_parse($txt)
        {
            // protect against missing data
            $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
            $data = array();
            $keys = implode('|', array_keys($needed_parts));
    
            preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);
    
            foreach ($matches as $m) {
                $data[$m[1]] = $m[3] ? $m[3] : $m[4];
                unset($needed_parts[$m[1]]);
            }
    
            return $needed_parts ? false : $data;
        }
    }