Skip to content

Instantly share code, notes, and snippets.

@ulfie22
Last active October 2, 2018 23:30
Show Gist options
  • Save ulfie22/f42bcba974255e626e828214c1292402 to your computer and use it in GitHub Desktop.
Save ulfie22/f42bcba974255e626e828214c1292402 to your computer and use it in GitHub Desktop.
Laravel Passport API Problem
<?php
namespace Tests\Feature\Feature;
use App\User;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class APITest extends TestCase
{
protected $access_tokens;
/**
* A basic test example.
*
* @return void
*/
public function testAPI()
{
$this->artisan('migrate:fresh');
$this->artisan('passport:install');
factory(User::class, 5)->create([
'password' => bcrypt('test12345')
]);
$secret = DB::table('oauth_clients')->where('id', 2)->value('secret');
$u1 = User::find(1);
$u2 = User::find(2);
$this->access_tokens['u1'] = $this->getTokenForUser($u1, $secret);
$this->access_tokens['u2'] = $this->getTokenForUser($u2, $secret);
dump($this->access_tokens);
$u1_response = $this->withHeaders($this->headersWithToken($this->access_tokens['u1']))
->json('GET','api/user')
->assertStatus(200)
->decodeResponseJson();
dump($u1_response);
$u2_response = $this->withHeaders($this->headersWithToken($this->access_tokens['u2']))
->json('GET','api/user')
->assertStatus(200)
->decodeResponseJson();
dump($u2_response);
$fail_response = $this->withHeaders($this->headersWithToken('this_is_not_a_real_token'))
->json('GET','api/user')
->assertStatus(200)
->decodeResponseJson();
dump($fail_response);
}
private function headersWithToken($token)
{
$headers = [
"Accept" => 'application/json',
"Authorization" => "Bearer " . $token,
'X-Spa-Host' => "test_domain.com"
];
return $headers;
}
private function getTokenForUser(User $user, $secret) {
$postData = [
"grant_type" => "password",
"client_id" => 2,
"client_secret" => $secret,
"username" => $user->email,
"password" => 'test12345',
"scope" => ""
];
$response = $this->json('POST', '/oauth/token', $postData)
->decodeResponseJson();
$access_token = $response['access_token'];
return $access_token;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment