![](/img/trans.png)
[英]In CakePHP Auth - is there a way to force https on all actions requiring Authentication (but not others)
[英]Laravel testing actions requiring authentication
我正在嘗試為我的 Laravel 應用程序編寫功能測試,但有些操作需要登錄。我該怎么做才能防止因未登錄而出錯? 我正在使用 JWTAuth。
我用 header Authorization
提出請求,准確地再現了現實世界中發生的事情。
我為我的測試用例創建了一個特征,並在需要身份驗證的地方使用:
在 trait 中,您為 header 授權中的用戶生成 JWT 有效令牌。 在這種情況下,我使用 Tymon package 進行 JWTAuth
<?php
namespace Tests\Feature;
use JWTAuth;
trait CallApiTrait {
/**
* Simulate call api
*
* @param string $endpoint
* @param array $params
* @param string $asUser
*
* @return mixed
*/
protected function callApi($endpoint, $method,$params = [], $email = 'user@email',$password='password')
{
$headers = [
'Accept'=>'application/json',
];
if($email&&$password){
$token = $token = JWTAuth::attempt(['email'=>$email,'password'=>$password]);
$headers['Authorization'] = 'Bearer ' . $token;
}
return $this->json(
$method,
$endpoint,
$params,
$headers
);
}
在我的測試方法中
class StudentTest extends TestCase {
use CallApiTrait;
...
public function test_can_request_with_auth(){
$rs = $this->callApi(route('foo.bar'),'GET');
$rs->assertStatus(200);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.