dounue1965
dounue1965
2015-11-09 07:01
浏览 98
已采纳

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

I am trying to write tests using Codeception in my Laravel 5 application specifically to test the web service. The authentication works using JWT tokens. I have successfully written and run a test that verifies a token being returned on authentication.

<?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();

Works like a charm. The problem I am facing is how to use the token returned here in other requests because obviously all other request will require a token to proceed so do I authenticate and fetch a new token before testing every API call or is there a way around this?

I can already do this:

<?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();

But this is not very efficient for the obvious reasons that I am hard coding the token. Any help is appreciated.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douqiang7462
    douqiang7462 2015-11-09 16:02
    已采纳

    You can grab the token from json by using call to $I->grabDataFromJsonResponse(). Example assumes your responses is something like:

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

    Then your test would be something like below. Warning, untested code.

    $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();
    
    点赞 评论
  • dongqian5569
    dongqian5569 2019-04-08 10:21

    you can define your general methods in ApiTester class which is located in _support directory, then you can reach it in all test classes

    this is what i do

    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'];
    
     }
    
    }
    

    and in my test classes I use it like this

    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);
      }
    }
    
    点赞 评论

相关推荐