I am building an API with stateless HTTP basic authentication in Laravel 5.2, as per documentation Stateless HTTP Basic Authentication , I have created following Middleware
app/Http/Middleware/AuthenticateOnceWithBasicAuth.php
<?php
namespace Illuminate\Auth\Middleware;
use Auth;
use Closure;
class AuthenticateOnceWithBasicAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return Auth::onceBasic() ?: $next($request);
}
}
And then registered it in Kernel.php
app/Http/kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'auth.basic.once' => \App\Http\Middleware\AuthenticateOnceWithBasicAuth::class,
];
I am using it in route as follows
Route::group(['prefix' => 'admin', 'middleware' => 'auth.basic.once'], function () {
Route::get('service/create', function () {
return response()->json(['name' => 'Abigail', 'state' => 'CA'], 200);
});
});
But it is giving me
ReflectionException in Container.php line 734: Class App\Http\Middleware\AuthenticateOnceWithBasicAuth does not exist
I have run following commands but with no success
composer dump-autoload
php artisan clear-compiled
php artisan optimize
Any help would be much appreciated. Thanks in advance.
Well first of all look at the namespaces:
namespace Illuminate\Auth\Middleware;
you should rename it to:
namespace App\Http\Middleware;
in the middleware you need to do something like this:
public function handle($request, Closure $next) {
if (!Auth::onceBasic()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With