使用LexikJWTauthenticationBundle Symfony 3.3获取现有用户的令牌

时间:2018-02-16 16:31:36

标签: jwt token symfony-3.3 lexikjwtauthbundle

我是单元测试中的菜鸟,我想测试我的API。 因此,当我尝试访问/ login_check路径和CRUL命令行时,LexikJWTAuthenticationBundle工作正常。 但是当我尝试使用TestCase时,我得到了这个错误:

1)测试\ AppBundle \ Controller \ StoreControllerTest :: testPOSTRate GuzzleHttp \ Exception \ ClientException:客户端错误:GET http://localhost:8000/api/stores导致401 Unauthorized响应: {"代码":401,"消息":"无效的JWT令牌"}

我的testPOST功能:

public function testPOSTRate(){
    $data = array(
      'rate' => 1,
      'store' => 1
    );
    // I'm not sure if it's the right way to get Token
    $token = $this->getService('lexik_jwt_authentication.encoder')->encode([
      'username' => 'Nacer',
      ]);

    $this->client->get('http://localhost:8000/api/stores', [
      'body' => json_encode($data),
      'headers' => [
        'Authorization' => 'Bearer '.$token
      ]
    ]);
  }

1 个答案:

答案 0 :(得分:0)

尝试以这种方式创建令牌

$userfull

其中UserInterfacedump($token);die;(用户对象)的实例。

为了确保令牌有效,您可以随时执行$this->get并查看。让我知道如果解决了你的问题。

注意我正在从控制器调用服务,这就是 'headers' => [ 'Authorization: Bearer '.$token ] 的原因。另外,您需要注入服务或服务容器才能访问所有服务。

如果不起作用,请添加此

{{1}}