请求头缺少授权信息 - Codeigniter rest

7

我正在使用Codeigniter rest server和firebase php-jwt创建RESTful服务。创建了一个API来返回operator的列表。客户端要访问这个API,必须在headers中发送令牌。示例请求如下:

GET /index.php/operators/prepaid HTTP/1.1
Host: testing.mydomain.in
Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjExNTIxNCIsImlhdCI6MTUxNzk4MjU1NywiZXhwIjoxNTE4MDAwNTU3fQ.PZYh3OlSsKGo_ihPPSm7RrU5BbTNaeTN1fKlNcOZ2r4
Cache-Control: no-cache
Postman-Token: 933f3b1d-7934-d30a-11bf-f80f3912f433

控制器代码:

use \Firebase\JWT\JWT;
class Operators extends REST_Controller 
{
    private $_payload;

    public function __construct($config = 'rest')
    {
        parent::__construct($config);
        $token = $this->input->get_request_header('Authorization');
        if(!$token) {
            $output = array("Error" => "Access Denied");
            $this->response($output, REST_Controller::HTTP_UNAUTHORIZED);
        }
        try {
            $this->_payload = JWT::decode($token, $this->config->item('jwt_secret_key'),array('HS256'));
        } catch (Exception $ex) {
            $output = array("Error" => $ex->getMessage());
            $this->response($output, REST_Controller::HTTP_UNAUTHORIZED);
        }
        $this->load->model('Operators_Data');
    }       

    public function prepaid_get()
    { 
        $operators = $this->Operators_Data->getOperatorsByService(1);
        $this->response($operators);
    }
}

我得到了以下结果。
{
     "Error": "Access Denied"
}

如果令牌不存在,则从控制器构造函数返回。但我在头部授权中发送了令牌。

这在我的本地主机上运行正常(它返回操作员列表)。但是当我尝试从测试服务器上运行时,它总是返回“拒绝访问”。

更新:非常确定服务器正在忽略“Authorization”标头。

也尝试过

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

.htaccess中的设置

非常感谢任何帮助。


你可以通过调用 http://php.net/manual/en/function.getallheaders.php 来获取所有的头信息。 - Brian Gottier
{ "用户代理": "PostmanRuntime / 7.1.1", "主机": "testing.mydomain.in", "Postman-Token": "e33c8281-15e0-46b9-88c1-26597780e33c", "连接": "保持连接", "接受": "/", "Accept-Encoding": "gzip,deflate", "缓存控制": "no-cache" } - The Megamind
所以你的授权标头缺失了。你确定在 Postman 请求中包含它了吗?因为看起来你没有包含它。 - Brian Gottier
我正在设置带有键“Authorization”的标头选项卡,并将返回的令牌作为值。不在“Authorisation”选项卡中。 - The Megamind
如果这篇文章对你有帮助,请查看它。https://dev59.com/YW_Xa4cB1Zd3GeqPzk0r - Dhaval Chheda
嘿 @TheMegamind,你是怎么解决的? - DoubleM
1个回答

7

添加

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

在我的情况下,在.htaccess文件的顶部解决了这个问题。


在将该代码添加到 .htaccess 文件后,它仍然无法正常工作。因此,我通过在 <VirtualHost *:80> 下添加 httpd-xampp.conf(如果您使用 XAMPP)来解决这个问题,这对我很有效。 - silverknightone
<IfModule mod_rewrite.c>
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.)$ index.php?/$1 [L] RewriteCond %{HTTP:Authorization} ^(.) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] #RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 </IfModule>
- user16249416

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接