php - 如何将变量发送到 Bramus 路由器
问题描述
我有一个使用 Bramus PHP 路由器并验证来自 Auth0 的 JWT 的 API 后端。这一切都很好,但我希望扩展功能并从 JWT 获取其他信息,然后我可以将这些信息传递给 API 调用。
也就是说,当用户进行 API 调用时,他们会将用户 ID 作为 URL 中的变量发送。但是,这个值已经在 JWT 中,所以为了安全起见,我想将用户 ID 从 JWT 中提取出来,而不是通过 URL 传递给它。
这是我尝试使用的路由代码片段:
....
$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 范围问题,而不是特定问题(bramus/router
我是该问题的作者)。由于您$user
在 before 可调用内定义,因此它仅在其当前范围内可用(例如,在函数的 the{
和 the之间}
)。因此,您无法在所述功能之外访问它。
有几种方法可以解决这个问题。由于我看到您已经$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')));
});
....
推荐阅读
- java - 单击投射图标时 Chromecast 崩溃
- razor - Razor 类库,不优先主 App
- excel - 使用 unicode 字符从本地 HTML 中抓取表格
- python - 如何在 python3 数据类中断言类型?
- html - 如何在当前菜单中创建下拉菜单
- java - 执行 findAll() 时 Spring boot 和 couchbase 中的 InvalidDataAccessResourceUsageException
- php - 当请求像“/example.php/”这样的.php但显示内容时,css不起作用
- amazon-web-services - AWS kubectl:无法连接到服务器:EOF
- java - 有没有更好的方法来交换玩家符号?
- android - 请迁移 JSON-RPC 和全局 HTTP 批处理端点 - Google Drive API