【问题标题】:How to send variables to Bramus Router如何将变量发送到 Bramus 路由器
【发布时间】:2019-01-28 17:06:19
【问题描述】:

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

也就是说,当用户进行 API 调用时,他们会将用户 ID 作为 URL 中的变量发送。但是,这个值已经在 J​​WT 中,所以为了安全起见,我想将用户 ID 从 JWT 中提取出来,而不是通过 URL 传递给它。

这是我尝试使用的路由代码的 sn-p:

....
  $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 jwt


    【解决方案1】:

    您在这里看到的问题是 PHP 范围问题,而不是特定的 bramus/router - 我是该问题的作者 - 问题。由于您在 before callable 中定义了$user,因此它仅在其当前范围内可用(例如,在函数的{} 之间)。因此,您无法在所述功能之外访问它。

    有几种方法可以解决这个问题。由于我看到您已经在 before 回调和其他函数中注入了一个 $app 变量,我建议您将 $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')));
      });
    ....
    

    【讨论】:

    • 当然!有时我被一个问题困住,只见树木不见森林。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多