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