首页 > 解决方案 > 如何将变量发送到 Bramus 路由器

问题描述

我有一个使用 Bramus PHP 路由器并验证来自 Auth0 的 JWT 的 API 后端。这一切都很好,但我希望扩展功能并从 JWT 获取其他信息,然后我可以将这些信息传递给 API 调用。

也就是说,当用户进行 API 调用时,他们会将用户 ID 作为 URL 中的变量发送。但是,这个值已经在 J​​WT 中,所以为了安全起见,我想将用户 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传递给路由器,以便在其他功能中使用它?

标签: phpjwt

解决方案


您在此处查看的问题是 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')));
  });
....

推荐阅读