php - 解决 PHP 中缺少 "Authorization"请求 header 的问题

标签 php jquery apache

我目前正在为一个 uni 项目开发 PHP REST API,该项目使用从使用 PhoneGap 的移动网络应用程序或我的桌面在开发过程中传递的 JSON 网络 token 。

当使用 ajax 将 token 发送到我的服务器页面“friends/read.php”时,服务器使用

正确获取授权 header
$headers = getallheaders();
$authHeader = $headers['Authorization'];

但在几次成功运行后停止这样做。在那之后,不再拾取 header 。

我的请求代码如下:

$.ajax({
    url: "http://localhost/chordstruck/api/friends/read.php",
    type: "GET",
    beforeSend: function (request) {
        request.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('jwt'));
    },
    datatype: "json",
    success: function (response) {
        console.log(response);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
    }
});

奇怪的是,当使用 die("test") 过早地终止 PHP 脚本然后再次删除 die() 时,服务器将开始为更多请求获取 Authorization header 。

读取.php:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization, X-Auth-Token');

$config = require_once '../config/core.php';
require_once '../config/jwt_helper.php';
// get database connection
include_once '../config/database.php';

// instantiate profile object
include_once '../objects/profile.php';

$headers = getallheaders();
$authHeader = $headers['Authorization'];

$token;

if ($authHeader) {

    list($jwt) = sscanf((string)$authHeader, 'Bearer %s');
    if ($jwt) {
        try {

            $key = $config['jwt_key'];
            $token = JWT::decode($jwt, $key, array('HS512'));

        } catch (Exception $e) {
            header('HTTP/1.0 401 Unauthorized');
            exit();
        }
    } else {
        header('HTTP/1.0 400 Bad Request');
        exit();
    }
} else {
    header('HTTP/1.0 400 No Header Found');
    exit();
}

echo "success";
?>

我在开发这个项目时遇到了一个 CORS 问题,我用上面的 header 以及我的 .htaccess 文件中的以下内容解决了这个问题:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

这可能是相关的吗?任何帮助/想法将不胜感激!

最佳答案

该问题似乎确实与 CORS 相关,在尝试多种方法后,以下解决方案现在有效。

将 read.php 中的 header 替换为:

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
    // you want to allow, and if so:
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        // may also be using PUT, PATCH, HEAD etc
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

归功于使用它来回答 CORS with php headers 的 slashingweapon

关于php - 解决 PHP 中缺少 "Authorization"请求 header 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55680234/

相关文章:

php - PHP 中的 Javascript .toString(16)

php - 尝试上传图像并让它更新mysql

php - Codeigniter - 具有多个参数的搜索表单

javascript - 使用 php 后端和 redux 在 React js 中实现动态元标记

apache - 无法在 Ubuntu 16.04 桌面上安装 mesos

jquery - 从检查值的 ajax 成功函数内部提交表单

JQuery 搜索关键字和样式最接近指定的 html 元素

javascript - JQuery 填充选择框,但发布选项消失后

php - 无法在我的 debian 404 Not Found 上访问 symfony 应用程序

php - 在 Rails 中处理数百个同时请求