如何在laravel 5中使用代码编写测试时重用JWT令牌?

时间:2015-11-09 07:01:13

标签: php laravel laravel-5 jwt codeception

我正在尝试使用我的Laravel 5应用程序中的Codeception来测试Web服务。身份验证使用JWT令牌。我已经成功编写并运行了一个测试,用于验证在身份验证时返回的令牌。

<?php
$I = new ApiTester($scenario);
$I->wantTo('authenticate a user');
$I->haveHttpHeader('Content-Type', 'application/x-www-form-urlencoded');
$I->sendPOST('authenticate', [
    'username' => 'carparts',
    'email' => 'admin@admin.com',
    'password' => 'password'
]);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();

像魅力一样工作。我面临的问题是如何在其他请求中使用此处返回的令牌,因为显然所有其他请求都需要令牌才能继续,因此我在测试每个API调用之前是否进行身份验证并获取新令牌?或者有解决方法吗? / p>

我已经可以这样做了:

<?php 
$I = new ApiTester($scenario);
$I->wantTo('see a list of all users');
$I->haveHttpHeader('Authorization', 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImNhcnBhcnRzIiwic3ViIjoiMSIsImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDAwXC9hcGlcL2F1dGhlbnRpY2F0ZSIsImlhdCI6IjE0NDY2NDA0ODYiLCJleHAiOiIxNDQ2NjQ0MDg2IiwibmJmIjoiMTQ0NjY0MDQ4NiIsImp0aSI6ImZmYTNkZjc4Yzg5YjdmNDNhYThkZTRmZTViZWI4YjI3In0.9UBZgEz3hHTEMlK5hPzYRV1DsAI3TSSHSZxV0FcBLio');
$I->sendGET('/users');
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();

但由于我很难对令牌进行编码,因此效率不高。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

您可以使用$I->grabDataFromJsonResponse()调用从json中获取令牌。示例假设您的回答类似于:

{
    "status": "ok",
    "token": "xxxxxxxx"
}

然后你的测试将如下所示。警告,未经测试的代码。

$I = new ApiTester($scenario);
$I->wantTo('authenticate a user');
$I->haveHttpHeader('Content-Type', 'application/x-www-form-urlencoded');
$I->sendPOST('authenticate', [
    'username' => 'carparts',
    'email' => 'admin@admin.com',
    'password' => 'password'
]);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();

$token = $I->grabDataFromJsonResponse('token');

$I->deleteHeader('Authorization'); /* Needed with old version of codeception. */
$I->amBearerAuthenticated($token);

$I->sendGET('/users');
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();

答案 1 :(得分:0)

您可以在_support目录中的ApiTester类中定义常规方法,然后在所有测试类中都可以使用它

这就是我所做的

class ApiTester extends \Codeception\Actor
{
   use _generated\ApiTesterActions;

   private $adminToken = null;

   public function getAdminToken()
   {
      if ($this->adminToken) {
         return $this->adminToken;
      }
      $this->generateAdminToken();
      return $this->adminToken;
   }

private function generateAdminToken()
{

    $email = 'adminTestUser@test.com';
    $password = '123456789';
    $I = $this;
    $encoder = new BCryptPasswordEncoder(12);
    $I->haveInDatabase('users', [
        'email' => $email,
        'kyc' => UserConstants::USER_KYC_LEVEL_MINIMUM,
        'status' => UserConstants::USER_STATUS_VERIFIED,
        'password' => $encoder->encodePassword($password, 'dasdsa'), // salt is not important for Bcrypt
        'created_at' => '2019-01-01 20:20:20',
        'updated_at' => '2019-01-01 20:20:20',
    ]);

    $userId = $I->grabFromDatabase('users', 'id', [
        'email' => $email
    ]);

    $I->haveInDatabase('roles', [
        'name' => 'ADMIN_PANEL_USER_ROLE2',
        'role' => 'ADMIN_PANEL_USER_ROLE2',

    ]);

    $roleId = $I->grabFromDatabase('roles', 'id', [
        'role' => 'ADMIN_PANEL_USER_ROLE2',
    ]);

    $I->haveInDatabase('user_role', [
        'user_id' => $userId,
        'role_id' => $roleId
    ]);


    $I->haveInDatabase('user_profiles', [
        'user_id' => $userId,
        'full_name' => 'testUser',

    ]);

    $I->haveHttpHeader('Content-Type', 'application/json');
    $I->sendPOST('/api/v1/auth/login', ['username' => $email, 'password' => $password]);
    $response = $I->grabResponse();
    $responseArray = json_decode($response, true);
    $this->adminToken = $responseArray['token'];

 }

}

在我的测试课程中,我像这样使用它

class UserControllerCest
{

  /**
   * @param ApiTester $I
  */
  public function testIndexAction(ApiTester $I)
  {
    $token = $I->getAdminToken();

    //we should login first
    $I->haveHttpHeader('Content-Type', 'application/json');
    $I->amBearerAuthenticated($token);
    $I->sendGET('/api/v1/posts');
    $I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK); // 200
    $this->seeSuccessfulResponseMatchesJsonTypes($I);
  }
}