diff --git a/tests/Middleware/AuthenticateTest.php b/tests/Middleware/AuthenticateTest.php new file mode 100644 index 000000000..567a98f76 --- /dev/null +++ b/tests/Middleware/AuthenticateTest.php @@ -0,0 +1,76 @@ + true]); + + // Register new test route with Authenticate middleware. This also tests the config in Kernel.php and auth.php. + Route::middleware('auth:api')->get(self::ENDPOINT, function (Request $request) { + return response()->json([ + 'email' => $request->user()->email, + ]); + }); + } + + public function testReturnsCustomJsonWhenUnauthenticated(): void { + $this->json('GET', self::ENDPOINT) + ->assertStatus(401) + ->assertJson(['error' => 'Unauthenticated.']); + } + + public function testAuthenticatesUsingPassportTokenFromCookie(): void { + $user = User::factory()->create(); + + $this->withCredentials() + ->withUnencryptedCookie(Config::get('auth.cookies.key'), $this->issueTokenFor($user)) + ->json('GET', self::ENDPOINT) + ->assertStatus(200) + ->assertJson(['email' => $user->email]); + } + + public function testFailsUsingInvalidPassportTokenFromCookie(): void { + $this->withCredentials() + ->withUnencryptedCookie(Config::get('auth.cookies.key'), 'this is an invalid token') + ->json('GET', self::ENDPOINT) + ->assertStatus(401) + ->assertJson(['error' => 'Unauthenticated.']); + } + + public function testAuthenticatesUsingPassportTokenFromAuthorizationHeader(): void { + $user = User::factory()->create(); + + $this->withCredentials() + ->withHeader('Authorization', 'Bearer ' . $this->issueTokenFor($user)) + ->json('GET', self::ENDPOINT) + ->assertStatus(200) + ->assertJson(['email' => $user->email]); + } + + public function testFailsUsingInvalidPassportTokenFromAuthorizationHeader(): void { + $this->withCredentials() + ->withHeader('Authorization', 'Bearer ' . 'this is an invalid token') + ->json('GET', self::ENDPOINT) + ->assertStatus(401) + ->assertJson(['error' => 'Unauthenticated.']); + } + + private function issueTokenFor(User $user): string { + return $user->createToken('authenticate-middleware-test')->accessToken; + } +}