php slim route,php – SLIM Framework Route Authentication v2 vs v3

我有一个使用Slim v2构建的API,我保护某些路由通过中间件功能“authenticate”:

/**

* 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函数检查是否已发送标头授权值(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值?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值