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

chiefguru's avatar

Can Basic HTTP Authentication be applied to an API route?

I have a collection of API routes, callbacks from a service, that I want to secure; however the service provider only supports basic http authentication (username and password).

I don't want to have to create a regular user account for the service provider if it can be avoided.

Is it possible to wrap these routes in 'auth_basic' middleware and supply a specific username and password?

0 likes
1 reply
LaryAI's avatar
Level 58

Yes, it is possible to apply Basic HTTP Authentication to an API route in Laravel. You can use the auth.basic middleware and provide a specific username and password in the config/auth.php file.

Here's an example of how to apply Basic HTTP Authentication to a specific API route:

Route::middleware('auth.basic')->get('/api/secure', function () {
    return response()->json(['message' => 'This is a secure API endpoint.']);
});

To provide a specific username and password, you can add them to the config/auth.php file:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],

    'basic' => [
        'driver' => 'basic',
        'provider' => 'users',
        'realm' => 'Restricted area',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
],

'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_resets',
        'expire' => 60,
    ],
],

In this example, we've added a new guard called basic that uses the basic driver and the users provider. We've also specified a realm for the authentication prompt.

Then, you can use the auth.basic:basic middleware to apply Basic HTTP Authentication to your API routes:

Route::middleware('auth.basic:basic')->get('/api/secure', function () {
    return response()->json(['message' => 'This is a secure API endpoint.']);
});

Now, when you access the /api/secure endpoint, you'll be prompted to enter a username and password. If you enter the correct credentials, you'll be able to access the endpoint.

Please or to participate in this conversation.