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

如何在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.

图片转代码服务由CSDN问答提供 功能建议

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

 &lt;?php 
 $ I = new ApiTester($ scenario); 
 $  I-&gt; wantTo('验证用户'); 
 $ I-&gt; haveHttpHeader('Content-Type','application / x-www-form-urlencoded'); 
 $ I-&gt; sendPOST(  'authenticate',[
'用户名'=&gt;'carparts',
'电子邮件'=&gt;'admin@admin.com',
'密码'=&gt;'密码'
 
]); \  n $ I-&gt; seeResponseCodeIs(200); 
 $ I-&gt; seeResponseIsJson(); 
 </ code> </ pre> 
 
 

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

我已经可以这样做了:</ p>

 &lt;?php 
 $ I = new ApiTester($ scenario); 
 $ I  - &GT; wantTo( '看到所有用户的列表'); 
 $的I-&GT; haveHttpHeader( '授权', '承载eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImNhcnBhcnRzIiwic3ViIjoiMSIsImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDAwXC9hcGlcL2F1dGhlbnRpY2F0ZSIsImlhdCI6IjE0NDY2NDA0ODYiLCJleHAiOiIxNDQ2NjQ0MDg2IiwibmJmIjoiMTQ0NjY0MDQ4NiIsImp0aSI6ImZmYTNkZjc4Yzg5YjdmNDNhYThkZTRmZTViZWI4YjI3In0.9UBZgEz3hHTEMlK5hPzYRV1DsAI3TSSHSZxV0FcBLio'); 
 $的I-&GT; sendGET('/用户 '); 
 $ I-&gt; seeResponseCodeIs(200); 
 $ I-&gt; seeResponseIsJson(); 
 </ code> </ pre> 
 
 

但这对于效率不高 我很难对令牌进行编码的明显原因。 任何帮助表示赞赏。</ p> </ div>

2条回答 默认 最新

相关推荐 更多相似问题