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

如何在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 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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?