Laravel的5.3身份验证不起作用

时间:2016-11-05 19:21:46

标签: php laravel-5

在我的Laravel 5.3身份验证中,我使用中间件来验证用户是否已登录以访问某些页面...

我面临的问题是que中间件总是会重定向到登录页面,即使我刚刚登录...

我的路线:

    Route::get('/', 'ProdutoController@lista');
Route::get('/produtos', 'ProdutoController@lista');
Route::get('/produtos/mostra/{id}', 'ProdutoController@mostra');
Route::get('/produtos/novo', 'ProdutoController@novo');
Route::post('/produtos/adiciona', 'ProdutoController@adiciona');
Route::get('produtos/lista-json', 'ProdutoController@listaJSON');
Route::get('/produtos/remove/{id}', 'ProdutoController@remove');
Auth::routes();
Route::get('/home', 'HomeController@index');
Route::get('/login', 'LoginController@form');
Route::post('/login', 'LoginController@login');

我的LoginController

class LoginController extends Controller
{
    public function form () {
        return view('form_login');
    }

    public function login () {
        // Credenciais (email e senha)
        $credenciais = Request::only('email', 'password');

        // Login
        if (Auth::attempt($credenciais)) { // caso as credenciais sejam aceitas, retorna true
            return 'Usuário ' . Auth::user()->name . ' logado com sucesso';
        }
        else {
            return 'Usuário não existe';
        }

    }
}

我的ProdutoController

class ProdutoController extends Controller
    {
        public function __construct()
        {
            $this->middleware('Autorizador');
        }

        public function lista()
        {

            $produtos = Produto::all();

            return view('produto/listagem')->with('produtos', $produtos);
        }
    }

我的核心:

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\Autorizador::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

我的中间件:

class Autorizador
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) // next é o código que será executado em seguida
    {

        if (!$request->is('login') && Auth::guest()) {
            return redirect('/login');
        }
        return $next($request);
    }
}

当我登录时,我收到消息,告诉我登录成功并向我提供了已记录用户的名称,但是当我尝试访问我的产品列表时,我被重定向到登录再次形成......

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我建议您Kernel.phpmiddleware而不是$routeMiddleware中添加$middleware作为:

Kernel.php

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'autorizador' => \App\Http\Middleware\Autorizador::class,
    ];
}

并在ProdutoController.php中将其用作:

public function __construct()
{
    $this->middleware('autorizador');
}