【问题标题】:check header Authorization on Restler API framework检查 Restler API 框架上的标头授权
【发布时间】:2011-10-25 13:06:08
【问题描述】:

我想扩展 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);
        }
    }
}
}

【问题讨论】:

    标签: php api rest


    【解决方案1】:

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

    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';
        }
    }
    

    我已经对其进行了测试以确保它可以正常工作!

    这里是如何使其与 Authorization 标头一起工作,它仅适用于 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:Authorization},last]

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

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

    【讨论】:

    • 感谢 Luracast,我已经做过这种方法,重要的是说客户坚持使用标头“授权”。
    • @Dee 给你,我已经用一个在标题中使用授权的工作示例更新了我的答案
    • 您好 Luracast,我尝试将其实现到您的 crud 示例中。但是,授权似乎是绕过的。我尝试了这个class Authorization implements iAuthenticate{ function __isAuthenticated(){ $headers = apache_request_headers(); return isset($headers['Authorization']) &amp;&amp; $headers['Authorization']=='password'; } },因为我怀疑我的 .htaccess 被忽略了。但仍然没有运气。有什么想法吗?
    【解决方案2】:

    标头认证

    三种方法

    1. HTTP 基本身份验证
    2. HTTP 摘要式身份验证
    3. 使用自定义 HTTP 标头滚动我们自己的

    您可以从PHP Manual阅读更多内容

    Restler 1.0 有一个摘要式身份验证示例。我已经修改以使其与 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;
        }
    }
    

    【讨论】:

    • 您好,Arul,感谢您的评论。除了 RESTler 的建议之外,您如何测试您的 API 服务器?
    猜你喜欢
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2019-06-17
    • 1970-01-01
    相关资源
    最近更新 更多