Laravel 检查所有请求中的登录名和 Auth::check()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32849779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:25:26  来源:igfitidea点击:

Laravel check login and Auth::check() in all of requests

phplaravellaravel-4

提问by

Using Laravel, 4 I'm checking the login session using Auth::check()in all of my controllers. This is not good for my project, so I'm try to check the user login session in all of requests and responses instead, by using a filter:

使用 Laravel,4 我正在检查Auth::check()所有控制器中使用的登录会话。这对我的项目不利,因此我尝试使用过滤器检查所有请求和响应中的用户登录会话:

App::before(function($request)
{
    if(!Auth::check()) {
        return Redirect::route('login');
    }
});

Unfortunately, I get this error:

不幸的是,我收到此错误:

The page isn't redirecting properly

How can I check the login session without using Auth::check()in routes and controllers?

如何在不使用Auth::check()路由和控制器的情况下检查登录会话?

采纳答案by Zahan Safallwa

Make your routes.php like following

使您的 routes.php 如下所示

Route::group(array('before' =>'auth'), function()
{
Route::get('something','HomeController@something');
});

In your filters.php bring changes to redirect to your desired route

在您的 filters.php 中进行更改以重定向到您想要的路线

Route::filter('auth', function()
{
if (Auth::guest())
{
    if (Request::ajax())
    {
        return Response::make('Unauthorized', 401);
    }
    else
    {
        return Redirect::guest('your_desired_route');
    }
 }
 });

So here login is checked in filters.php not routes.php or controllers.

所以这里登录是在filters.php而不是routes.php或控制器中检查的。

回答by Zsw

The real problem here is that you have an infinite redirect loop. App::beforewill apply to every single request.... including the request to Redirect::route('login').

这里真正的问题是你有一个无限重定向循环。App::before将适用于每一个请求.... 包括对Redirect::route('login').

Thus upon redirecting to the login page, you immediately redirect again to the login page, and so on. Your browser will detect the infinite redirect, stop it, and tell you The page isn't redirecting properly.

因此,在重定向到登录页面时,您会立即再次重定向到登录页面,依此类推。您的浏览器将检测到无限重定向,将其停止并告诉您The page isn't redirecting properly

One way to get around this is to use the Request::is()method to detect whether you are already on the login page. If you are, don't redirect again.

解决此问题的Request::is()一种方法是使用该方法来检测您是否已经在登录页面上。如果是,请不要再次重定向。

if (!Auth::check() && !Request::is('login')) {
    return Redirect::route('login');
}

回答by akbarbin

It looks like you have a problem with your redirect page. You just change

您的重定向页面似乎有问题。你只要改变

App::before(function($request)
{
    if (Auth::check()) {
         return Redirect::to('admin/dashboard');
    } else {
         return View::make('login')
    }
});