Antonella's avatar

test APi token with permissions problem

i generated two tokens:

tokenA = As2 ... xxxxx //can perform ONLY  create
tokenB = Bs2 ... xxxxx //can perform ONLY update

i have the following problem

$response = $this->withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer '.$tokenA],
        ])->post('/api/store',$data);
        $response->assertStatus(201);

//the store is made without problems

$response = $this->withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer '.tokenB,
        ])->put('/api/update',$dataUpdate);
        $respone->assertStatus(200);

//the test fails and returns 403. As if you don't have permission to do that

while if I call only

$response = $this->withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer '.tokenB,
        ])->put('/api/update',$dataUpdate);
        $response->assertStatus(200);

the update is performed without problems.

How can I run the store and then the update in sequence?

it appears that $ response continues to hold the value of tokenA

0 likes
6 replies
Sergiu17's avatar

Try to clear the headers before you send update request

$response = $this->withHeaders( ...

$this->flushHeaders(); // this line

$response = $this->withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer '.tokenB,
        ])->put('/api/update',$dataUpdate);
        $respone->assertStatus(200);
Antonella's avatar

Expected status code 200 but received 403. Failed asserting that 200 is identical to 403.

same result :-( @sergiu17

$response = $this->withHeaders([ 'Accept' => 'application/json', 'Authorization' => 'Bearer '.$tokenA], ])->post('/api/store',$data); $response->assertStatus(201);

$this->flushHeaders()

$response = $this->withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer '.tokenB,
        ])->put('/api/update',$dataUpdate);
        $respone->assertStatus(200);
Sergiu17's avatar

@gianmarx and if you try to set header as a third parameter of put method, still doesn't work?

$this->put('/api/update', $dataUpdate, [
	'Accept' => 'application/json',
	'Authorization' => 'Bearer '.tokenB,
])
->assertStatus(200);
Antonella's avatar

Expected status code 200 but received 403. Failed asserting that 200 is identical to 403.

same result @sergiu17

Antonella's avatar

it only works if you put the store in one method and update it in another method. It seems to me a bad solution @sergiu17

Antonella's avatar

ok I found that it fails when I do this check in the update $ request->user()->tokenCan('update') basically I don't update the user. does the old user remain set and the check fails? @sergiu17

Please or to participate in this conversation.