Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReflectionException - Middleware class does not exist Laravel 5.2

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

enter image description here

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.

like image 950
Devendra Verma Avatar asked Jun 01 '16 12:06

Devendra Verma


1 Answers

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);
}
like image 134
Filip Koblański Avatar answered Nov 14 '22 17:11

Filip Koblański