Php 如何将变量发送到Bramus路由器
我有一个API后端,它使用Bramus PHP路由器并从Auth0验证JWTs。这一切都很好,但我希望扩展功能并从JWT中获得附加信息,然后将这些信息传递给API调用 也就是说,当用户进行API调用时,他们将用户ID作为URL中的变量发送。但是,这个值已经在JWT中了,所以为了安全起见,我想从JWT中提取用户ID,而不是通过URL传递给用户 下面是我尝试使用的路由代码的一个片段:Php 如何将变量发送到Bramus路由器,php,jwt,Php,Jwt,我有一个API后端,它使用Bramus PHP路由器并从Auth0验证JWTs。这一切都很好,但我希望扩展功能并从JWT中获得附加信息,然后将这些信息传递给API调用 也就是说,当用户进行API调用时,他们将用户ID作为URL中的变量发送。但是,这个值已经在JWT中了,所以为了安全起见,我想从JWT中提取用户ID,而不是通过URL传递给用户 下面是我尝试使用的路由代码的一个片段: .... $router->before('GET|POST', '/api.*', function()
....
$router->before('GET|POST', '/api.*', function() use ($app) {
$userid = '12345';
});
// Check for read:messages scope
$router->before('GET', '/api/private-scoped', function() use ($app) {
if (!$app->checkScope('read:messages')){
header('HTTP/1.0 403 forbidden');
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array("message" => "Insufficient scope."));
exit();
}
});
$router->get('/api/users/get-info/(\w+)', function($userid) use ($app) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode($app->getUserInfo($userid));
});
$router->get('/api/users/test', function() {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array("user" => $userid));
});
....
当我访问/api/users/test
时,我得到以下响应:
{
"user": null
}
如何将变量
$userid
传递到路由器,以便在其他函数中使用它?您在这里看到的问题是一个PHP范围问题,而不是一个具体的问题,我是该问题的作者。由于在before callable中定义了$user
,因此它仅在其当前范围内可用(例如,在函数的{
和}
之间)。因此,您不能在上述功能之外访问它
有几种方法可以解决这个问题。因为我看到您已经将$app
变量注入before回调和其他函数,所以我建议您将$userid
存储到$app
中,并始终从那里读取它
大概是这样的:
....
$router->before('GET|POST', '/api.*', function() use ($app) {
$app->set('userid', '12345');
});
// Check for read:messages scope
$router->before('GET', '/api/private-scoped', function() use ($app) {
if (!$app->checkScope('read:messages')){
header('HTTP/1.0 403 forbidden');
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array("message" => "Insufficient scope."));
exit();
}
});
$router->get('/api/users/get-info/(\w+)', function($userid) use ($app) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode($app->getUserInfo($userid));
});
$router->get('/api/users/test', function() use ($app) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array("user" => $app->get('userid')));
});
....
当然有时我遇到问题就束手无策,看不见森林,看不见树木。非常感谢。