简体   繁体   English

Laravel - 如果用户未经过身份验证,如何重定向到登录

[英]Laravel - How to redirect to login if user is not authenticated

I'm trying to use the __constructor from the extended class ( AdminController extends AdminBaseController ) but aparently it's not working and I have no idea of what can be, here you can see both of my classes: 我正在尝试使用扩展类中的__constructorAdminController扩展AdminBaseController ),但显然它不起作用,我不知道它可以是什么,在这里你可以看到我的两个类:

AdminBaseController.php AdminBaseController.php

class AdminBaseController extends Controller
{
    public function __construct(){
        if (!Auth::user()){
            return view('admin.pages.login.index');
        }
    }
}

AdminController.php AdminController.php

class AdminController extends AdminBaseController
{
    public function __construct(){
        parent::__construct();
    }

    public function index()
    {
        return view('admin.pages.admin.index');
    }

    public function ajuda()
    {
        return view('admin.pages.admin.ajuda');
    }
}

EDIT 编辑


This is my admin route group: 这是我的admin路由组:

Route::group([
    'prefix' => 'admin',
    'middleware' => 'auth'
], function () {
    Route::get('/', 'Admin\AdminController@index');

    Route::get('login', 'Admin\AuthController@getLogin');
    Route::post('login', 'Admin\AuthController@postLogin');
    Route::get('logout', 'Admin\AuthController@getLogout');

    Route::group(['prefix' => 'configuracoes'], function () {
        Route::get('geral', 'Admin\AdminConfiguracoesController@geral');
        Route::get('social', 'Admin\AdminConfiguracoesController@social');
        Route::get('analytics', 'Admin\AdminConfiguracoesController@analytics');
    });

    Route::get('ajuda', 'Admin\AdminController@ajuda');
});

The controller is not the right place to check if a user is authenticated or not. 控制器不是检查用户是否经过身份验证的正确位置。 You should use a middleware for that. 你应该使用中间件。 To get info on what a middleware is check here 要获取有关中间件检查的信息,请访问此处

Let's see how you can use the default Laravel's auth middleware for this purpose: 让我们看看如何使用默认的Laravel的auth中间件来实现此目的:

First of all get rid of your AdminBaseController and use only AdminController 首先摆脱AdminBaseController并仅使用AdminController

Then you have to check that the auth middleware is enabled in the file app\\Http\\Kernel.php 然后你必须检查文件app\\Http\\Kernel.php是否启用了auth中间件

You should have the line: 你应该有这条​​线:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,

This means that the middleware is active and usable for your routes. 这意味着中间件是活动的并且可用于您的路由。

Now let's go inside the middleware class in app\\Http\\Middleware\\Authenticate.php to specify the middleware's behaviour : 现在让我们进入app\\Http\\Middleware\\Authenticate.php的中间件类来指定中间件的行为:

//this method will be triggered before your controller constructor
public function handle($request, Closure $next)
{
    //check here if the user is authenticated
    if ( ! $this->auth->user() )
    {
        // here you should redirect to login 
    }

    return $next($request);
}

Now the only thing left to do is to decide for what routes you should apply the middleware. 现在唯一要做的就是决定应该应用中间件的路由。 Let's suppose you have two routes that you want to be only accessible from authenticated users, you should specify to use the middleware for these two routes in this way: 假设您有两条路径只能从经过身份验证的用户访问,您应该指定以这种方式使用这两条路由的中间件:

Route::group( ['middleware' => 'auth' ], function()
{
    Route::get('admin/index', 'AdminController@index');
    Route::get('admin/ajuda', 'AdminController@ajuda');
});

Use middleware for this purpose and then in controller constructor use it as in example below. 为此目的使用中间件,然后在控制器构造函数中使用它,如下例所示。

public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
}

And then you need to secure routes where you want from user to be logged in to access. 然后,您需要保护您希望用户登录的路由以进行访问。

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

In Laravel 5.5 , an unauthenticated user will cause the Authenticate middleware to throw a AuthenticationException exception. 在Laravel 5.5中,未经身份验证的用户将导致Authenticate中间件抛出AuthenticationException异常。

protected function authenticate(array $guards)
{
 if (empty($guards))
 {
  return $this->auth->authenticate();
 }
 foreach ($guards as $guard) {
  if ($this->auth->guard($guard)->check()) {
      return $this->auth->shouldUse($guard);
  }
 }
 throw new AuthenticationException('Unauthenticated.', $guards);
}

This will be caught by the app/Exceptions/Handler class which will call its render method which is responsible for converting a given exception into a HTTP response. 这将由app / Exceptions / Handler类捕获,该类将调用其render方法,该方法负责将给定异常转换为HTTP响应。

public function render($request, Exception $exception)
{
 return parent::render($request, $exception);
}

App/Exceptions/Handler extends 'Illuminate\\Foundation\\Exceptions\\Handler', located inside '/vendor/laravel/src/Illuminate/Foundation/Exceptions/Handler'. App / Exceptions / Handler扩展了'Illuminate \\ Foundation \\ Exceptions \\ Handler',位于'/ vendor / laravel / src / Illuminate / Foundation / Exceptions / Handler'中。 It has its own render method. 它有自己的渲染方法。 Within that render method, there's a if else statement that says. 在该render方法中,有一个if else语句。

elseif ($e instanceof AuthenticationException)
{
 return $this->unauthenticated($request, $e);
}

Below is the 'unauthenticated' method that is called by the above within the same class 下面是上面在同一个类中调用的'unauthenticated'方法

protected function unauthenticated($request, AuthenticationException $exception)
{
  return $request->expectsJson() ? response()->json(['message' => $exception->getMessage()], 401) : redirect()->guest(route('login'));
}

within this method is where you redirect an unauthenticated user. 在此方法中,您可以重定向未经身份验证的用户。

As far as I can see, this is what goes on behind the scenes. 据我所知,这是幕后发生的事情。

The way you extends and execute the parent constrictor is right, however returning a view to execute it is only possible from routes, controller actions and filters. 扩展和执行父缩写器的方式是正确的,但是只能从路由,控制器操作和过滤器返回执行它的视图。 Otherwise you have to call send(). 否则你必须调用send()。

for you purpose I think you should use before for filter http://laravel.com/docs/4.2/routing#route-filters 为了你的目的,我认为你应该使用之前的过滤器http://laravel.com/docs/4.2/routing#route-filters

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

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