简体   繁体   English

Laravel Json 测试带Bearer认证

[英]Laravel Json test with Bearer authentication

I'm writing a simple test to assert if an api endpoint response returns with 200 status.我正在编写一个简单的测试来断言 api 端点响应是否返回 200 状态。

My api got Bearer authentication through sanctum middleware.我的 api 通过sanctum中间件获得了 Bearer 认证。

My test function is我的测试 function 是

 public function testExample() { // $response = $this->withHeader('Authorization', 'Bearer 1|IJleXxjHgr8RaiP3Q9atJRtVCZHZKQQqBXW8NPdn') // ->getJson('/api/breeds/cat/high'); $response = $this->getJson('/api/breeds/cat/high', ['Authorization' => 'Bearer longtoken']); $response->assertStatus(200); }

routes/api.php;路线/api.php;

> Route::middleware('auth:sanctum')->group(function () {
>     Route::get('/breeds/{animal_type}/{name}', ListBreeds::class)->name('breed.list'); });

This test returns me with 403 / Not Authorised response.该测试返回 403 / Not Authorized 响应。 If I use the same token and headers in Postman the route works fine.如果我在 Postman 中使用相同的令牌和标头,则路由可以正常工作。

what is it I'm doing wrong?我做错了什么?

Thanks in advance.提前致谢。

It should be like that:它应该是这样的:

$response = $this->withHeaders([
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer ' . 'abc',
    ])->getJson('/api/breeds/cat/high');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM