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

hellopeter13's avatar

Protecting Laravel Api with Auth Middleware

Hi,

We are using laravel breeze template for authentication, now we want to make few request to /api in our application.

Now some API will be protected, so we implemented following suggestion Laravel Stateless Rest API

Now when we are making request to /api/v1/get-students we are getting a popup asking to login (javascript popup)

Here is what we have done

created following model

File AuthenticateOnceWithBasicAuth

class AuthenticateOnceWithBasicAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        return Auth::onceBasic() ?: $next($request);
    }
}

API file

routes/api.php

Route::prefix('v1')
    ->middleware(['auth.basic'])
    ->group(function () {
        Route::get('get-students', function () {
            return 'hello';
        })->name('get-api-students');
    });

Getting this when visiting the page protected by auth middleware

this page is making the API request

Popup

0 likes
2 replies
martinbean's avatar

@hellopeter13 Well, yes. That’s what basic authentication is: it prompts for a username and password. So it’s not what you want for an API. At all.

Instead you should be using some form of cookie or token-based authentication, such as that provided by Sanctum.

Also, “get-students” isn’t really a conventional name for an API endpoint. If you’re building a REST-like API then define REST-like routes. Your URI would be something like /api/v1/students instead, and then depending on what HTTP method you use to access the URI would depend on what controller method is called. Laravel calls these resource controllers.

hellopeter13's avatar

Hi, so should I rewrite the whole authentication or it will work with existing setup?

BTW thanks for the tip about naming convention :)

Please or to participate in this conversation.