Sending proper authentication request HTTP headers with phpunit for Laravel basic auth middleware

Submitted by Novica89 - 8 years ago

Bumped into a problem while trying to authorize user against laravel basic auth middleware when testing a REST API through phpunit. I used phpunit call method to send a POST request to API's endpoint which needed users basic HTTP authentication. Every time, laravels basic auth middleware rejected it and I had no idea why, since I've sent proper HTTP Authorization header with phpunit call. Here is the solution ! Or watch it in a video https://www.youtube.com/watch?v=LCrt7jqDsgU Read more on http://laravel.io/forum/03-20-2014-authbasic-fails

/**
     * @test
     */
    public function existing_user_can_create_new_book_which_gets_assigned_to_him()
    {
        // given we have a registered user
        $user = factory("App\\User")->create();

        // when this user tries to create a new book
        $this->call("POST", "api/v1/book", [
            "title" => "Amazing book of REST APIs",
            "language" => "English",
            "original_language" => "Serbian",
            "publishing_year" => "2004",
            "authors" => "Nick Wright,SomeGuy Great"
        ],[], [], [
            "HTTP_Authorization" => "Basic " . base64_encode($user->username . ":" . "password"),
            "PHP_AUTH_USER" => $user->username, // must add this header since PHP won't set it correctly
            "PHP_AUTH_PW" => "password" // must add this header since PHP won't set it correctly as well
        ]);

        // then a new book should be created for that user
        $this->assertResponseStatus(201);
        $this->seeInDatabase("books", [
            "title" => "Amazing book of REST APIs",
            "user_id" => $user->id
        ]);

    }