Search code examples
phplaravellaravel-5jwtcodeception

How to reuse JWT tokens while writing testing using codeception in laravel 5?


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' => '[email protected]',
    '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.


Solution

  • 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' => '[email protected]',
        '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();