Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Oldenborg's avatar

Testing auth.basic

I havent worked with Laravel since Laravel 5.6 and Im getting back into Laravel now.

Im working on a small API where I have a webhook I want to protect with basic HTTP Authentication

How would I write a test that sends the correct headers with the request to check if I can access a route that is protected with the auth.basic middleware?

0 likes
4 replies
Sinnbeck's avatar

Just to make sure. Are we talking about "basic session based authentication in laravel". Or are we talking apache2/nginx basic auth ?

Oldenborg's avatar

I'm talking about this HTTP Basic Authentication

MyTest.php

<?php

namespace Tests\Feature;

use \App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    use RefreshDatabase, WithFaker;

    public function testProtectedRoute()
    {
        // Set the basic auth credentials to use in the request
        $email ='[email protected]';
        $pwd = 'testpassword';

        User::factory()->create([
            'email' => $email,
            'password' => $pwd,
        ]);

        // Make a request to the protected route using the basic auth credentials
        $response = $this->withHeaders([
            'Authorization' => 'Basic '.base64_encode($email.':'.$pwd),
        ])->get('/api/protected-route');

        // Assert that the request was successful
        $response->assertStatus(200);
    }
}

routes/api.php

Route::get('/protected-route', function () {
    // Only authenticated users may access this route...
    return 200;
})->middleware('auth.basic');

I would think this should work but I keep getting a 401 Http response, meaning I'm not authenticated

Oldenborg's avatar
Oldenborg
OP
Best Answer
Level 6

Still need help figuring this out

Oldenborg's avatar

I fixed this by adding this to the User model

/**
 * Password need to be all time encrypted.
 *
 * @param string $password
 */
public function setPasswordAttribute($password)
{
    $this->attributes['password'] = bcrypt($password);
}

Please or to participate in this conversation.