简体   繁体   English

Laravel 5 中间件验证总是失败并重定向到登录

[英]Laravel 5 middleware auth always fails and redirects to login

I am authenticating my user and redirecting him to dashboard if credentials are correct.如果凭据正确,我正在验证我的用户并将他重定向到仪表板。 I want to secure the dashboard route and added middleware auth, but now it always redirects to login page.我想保护仪表板路由并添加中间件身份验证,但现在它总是重定向到登录页面。

Routes.php路线.php

Route::get('login', array('uses' => 'HomeController@showLogin'));
Route::post('login', array('uses' => 'HomeController@doLogin'));
Route::get('logout', array('uses' => 'HomeController@doLogout'));

Route::group(['middleware' => 'auth'], function() {
    Route::get('/', function () {
        return view('dashboard');
    });
    Route::get('dashboard', function () {
        return view('dashboard');
    });
});

HomeController.php家庭控制器.php

public function showLogin(){
    return View::make('login');
}

public function doLogin(Request $request){
    $rules = array(
        'email'    => 'required|email',
        'password' => 'required|alphaNum|min:3'
    );
    $validator = Validator::make($request::all(), $rules);
    if ($validator->fails()) {
        return Redirect::to('login')
            ->withErrors($validator)
            ->withRequest($request::except('password'));
    }
    else {
        $userdata = array(
            'email'     => $request::get('email'),
            'password'  => $request::get('password')
            /*'password' => Hash::make($request::get('password'))*/
        );
        if (Auth::attempt($userdata)) {
            $userid = Auth::id();
            return redirect()->intended('/');
        } else {
            return Redirect::to('login');
        }
    }
}

public function doLogout()
{
    Auth::logout();
    return Redirect::to('login');
}

Middleware Authenticate.php中间件Authenticate.php

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login');
        }
    }

    return $next($request);
}

Middleware RedirectIfAuthenticated.php中间件RedirectIfAuthenticated.php

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect('/');
    }

    return $next($request);
}

I am not sure why your code is not working, but you can try replace: 我不确定为什么您的代码无法正常工作,但是您可以尝试替换:

if (Auth::attempt($userdata)) {
    $userid = Auth::id();
    return redirect()->intended('/');
}

with: 有:

if (Auth::attempt($userdata)) {
    $userid = Auth::id();
    return redirect('dashboard');
}

From the API Docs of intended method : 预期方法API文档中

Create a new redirect response to the previously intended location. 创建到先前预定位置的新重定向响应。

is giving some error to you as it is going back to the previous location and not to the next location. 返回到上一个位置而不是下一个位置,这给您带来一些错误。


UPDATE 1: 更新1:

I would have gone with the following approach. 我本来会采用以下方法。

Make your own middleware called UserAlreadyLoggedIn 制作自己的中间件,称为UserAlreadyLoggedIn

php artisan make:middleware UserAlreadyLoggedIn

Open UserAlreadyLoggedIn.php and update handle method with the below code: 打开UserAlreadyLoggedIn.php并使用以下代码更新句柄方法:

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    if(auth()->check()) {
        return $next($request);
    }

    return redirect('login');
}

Register it in app/Http/Kernel.php file inside $routeMiddleware array: $routeMiddleware数组中的app/Http/Kernel.php文件中注册它:

$routeMiddleware = [
    'user_already_logged_in' => \App\Http\Middleware\UserAlreadyLoggedIn::class,
];

Separate the already logged in user in controller by making UserSessionsController 通过使UserSessionsController分离控制器中已登录的用户

php artisan make:controller UserSessionsController --plain

Inside UserSessionsController place the __constructor method: UserSessionsController内部放置__constructor方法:

/**
 * Check if the user is already logged in.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('user_already_logged_in');
}

routes.php routes.php文件

Route::get('login', 'HomeController@showLogin');
Route::post('login', 'HomeController@doLogin');
Route::get('logout', 'HomeController@doLogout');

// Replace the dashboard code inside the dashboard method..
Route::get('dashboard', 'UserSessionsController@dashboard');

Again I would have created a middleware called UserIsAGuest and would have replaced the if block inside the handle method: 同样,我将创建一个名为UserIsAGuest的中间件,并将替换handle方法中的if块:

if(auth()->guest()) {
    return $next($request);
}
return redirect('dashboard');

And then inside the HomeController 's __construct method: 然后在HomeController__construct方法中:

/**
 * Check if the user is already logged in.
 *
 * @return void
 */
public function __construct()
{
    // Register the middleware in Kernel.php file
    $this->middleware('user_is_guest');
}

Hope this helps you out. 希望这可以帮助你。 Happy Coding. 编码愉快。 Cheers. 干杯。

Sorry for being late to the party, but after a long search for me, I had to change my middleware from ['middleware' => 'auth] to ['middleware' => 'auth:web']很抱歉来晚了,但经过长时间的搜索,我不得不将我的中间件从['middleware' => 'auth]更改为['middleware' => 'auth:web']

I hope this helps out我希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM