SLIM框架路由身份验证v2与v3


SLIM Framework Route Authentication v2 vs v3

我有一个用Slim v2构建的API,我通过中间件功能"验证"来保护某些路由:

    /**
     * List marca novos
     * method GET
     * url /novos/marca/:idmarca
     */
    $app->get('/novos/marca/:idmarca', 'authenticate', function($idmarca) {
        $response = array();
        $db = new DbHandler('dbnovos');

        // fetching marca
        $marca = $db->getMarcaNovos($idmarca);
        $response["error"] = false;
        $response["marca"] = array();
        array_walk_recursive($marca, function(&$val) {
            $val = utf8_encode((string)$val);
        });
        array_push($response["marca"], $marca);
        echoRespnse(200, $response, "marcaoutput");
    })->via('GET', 'POST');

authenticate函数检查是否发送了头Authorization值(user_api_key),并对照数据库进行检查。

我正在尝试在Slim v3 API中使用以下路由获得相同的功能:

    /**
     * List marca novos
     * method GET
     * url /novos/marca/:idmarca
     */
    $app->get('/novos/marca/{idmarca}', function ($request, $response, $args) {
    $output = array();
    $db = new DbHandler('mysql-localhost');
    $marca = $db->getMarcaNovos($args['idmarca']);
    if ($marca != NULL) {
        $i = 0;
        foreach($marca as $m) {
            $output[$i]["id"] = $m['id'];
            $output[$i]["nome"] = utf8_encode($m['nome']);
            $i++;
        }
    } else {
        // unknown error occurred
        $output['error'] = true;
        $output['message'] = "An error occurred. Please try again";
    }
    // Render marca view
    echoRespnse(200, $response, $output, "marca");
})->add($auth);

这是我的中间件

/**
 * Adding Middle Layer to authenticate every request
 * Checking if the request has valid api key in the 'Authorization' header
 */
$auth = function ($request, $response, $next) {
$headers = $request->getHeaders();
$outcome = array();
// Verifying Authorization Header
if (isset($headers['Authorization'])) {
    $db = new DbHandler('mysql-localhost');
    // get the api key
    $api_key = $headers['Authorization'];
    // validating api key
    if (!$db->isValidApiKey($api_key)) {
        // api key is not present in users table
        $outcome["error"] = true;
        $outcome["message"] = "Access Denied. Invalid Api key";
        echoRespnse(401, $outcome, $output);
    } else {
        global $user_id;
        // get user primary key id
        $user_id = $db->getUserId($api_key);
        $response = $next($request, $response);
        return $response;
    }
} else {
    // api key is missing in header
    $outcome["error"] = true;
    $outcome["message"] = "Api key is missing";
    //echoRespnse(400, $response, $outcome);
    return $response->withStatus(401)->write("Not allowed here - ".$outcome["message"]);
}
};

但我总是得到错误:"这里不允许-Api密钥丢失"基本上,如果设置了$headers["Authorization"],则测试将失败。$headers数组结构是什么?或者我如何获得通过标头传递的Authorization值?

如果您发送的不是有效的HTTP Basic Authorization标头,PHP将无法访问它。您可以通过在.htaccess文件中添加以下重写规则来解决此问题。

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