【问题标题】:Laravel 5 deny route for non auth usersLaravel 5拒绝非身份验证用户的路由
【发布时间】:2023-03-07 19:29:06
【问题描述】:

我有这个 Laravel 5 应用程序。有两个控制器:Index 和 Home。 在索引中,我有尚未登录的用户可见的页面。当用户登录时,他会转到家庭控制器。 当然,我希望访问者无法查看家庭控制器下的路线。 因此,我在 Home 的构造函数中进行了检查。但它重定向回索引,似乎根本不是正确的方法。 所以有这组路线:

Route::group(['prefix' => '/home'], function () {
    Route::auth();
    Route::get('index', 'HomeController@index');
    Route::get('logout', 'HomeController@logout');
});

如您所见,我添加了。

Route::auth();

我认为应该设法拒绝尚未登录的访问者访问。尚未登录的用户仍然可以访问主页。

在 route.php 中直接描述一堆路由(我猜是在一个组内)在提供路由之前应该先经过身份验证的方法是什么?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您是否在控制器中使用此代码?

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

    【讨论】:

      【解决方案2】:

      您应该添加一个auth 中间件来保护您的home 组:

      Route::auth();
      
      Route::group(['middleware' => 'auth'], function() {
          Route::group(['prefix' => '/home'], function () {
              Route::get('index', 'HomeController@index');
              Route::get('logout', 'HomeController@logout');
          });
      });
      

      你可以看看这个:https://laravel.com/docs/5.2/authentication#protecting-routes

      【讨论】:

        【解决方案3】:

        在 Laravel 中非常简单,您只需使用单个 Middleware

        看到这个DOC

        前:

        Route::get('profile', ['middleware' => 'auth', 'uses' => 'ProfileController@show']);
        

        此配置文件显示路线仅在用户登录时有效。

        如果您有多个路由要防止未经身份验证的用户,请使用路由组,

        Route::group(['prefix' => '/home', 'middleware' => ['auth']], function()
        {
            // user need to logged in order to access these routes
            Route::get('/', function()
            {
        
            });
        });
        

        【讨论】:

          【解决方案4】:
          1. 在 kernal.php 中添加 'auth' => 'MyespaceAdmin\Http\Middleware\Authenticate' in $routeMiddleware。
          2. 中间件目录中的Authenticate.php检查以下代码的句柄函数。

            if ($this->auth->guest()) {
                if ($request->ajax()) {
                    return response('Unauthorized.', 401);
                } else {
                    return redirect()->guest('your login page url');
                }
            }
            
          3. 然后在路由或控制器中使用中间件身份验证

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-04-06
            • 1970-01-01
            • 1970-01-01
            • 2016-02-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-05-16
            相关资源
            最近更新 更多