本文介绍了使用Laravel验证的中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Laravel 5.1真的有最低限度的文件..
我需要有关如何使用保护线路清晰的概念验证middileware ..

Laravel 5.1 really had minimal documentation..I need clear idea about how to protect routes using Auth middileware..

文档讲述到中间件=>身份验证参数添加到路由。
还是能做到的。

Documentation tells to add "middleware" => "auth" parameter to route.or can do

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

但如何从受保护的路径??使用验证的中间件实际用户认证和自动重定向到/登录

But How to use Auth middleware for actual user authentication and auto redirection to /login from protected routes ??

推荐答案

在Kernel.php - 有注册保护下$ routeMiddleware中间件是这样的:

In Kernel.php - there are registered middlewares under protected $routeMiddleware like this:

/**
 * The application's route middleware.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
];

您可以看到身份验证被注册为使用App \\ HTTP \\中间件\\验证。

You can see 'auth' is registered for using App\Http\Middleware\Authenticate.

然后你就可以走这条路 - 如果你开的 /app/Http/Middleware/Authenticate.php
你会发现公共职能句柄:

Then you can follow this path - if you open /app/Http/Middleware/Authenticate.php,you will find public function handle:

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest())
        {
            if ($request->ajax())
            {
                return response('Unauthorized.', 401);
            }
            else
            {
                return redirect()->guest('auth/login');
            }
        }

        return $next($request);
    }

和这里是重定向进行管理,你可以修改它根据自己的需要,也可以创建自定义的中间件。

and here is where redirection is managed, and you can modify it for your own needs, or you can create custom middleware.

最后 - 因为它是写在文件 - 在控制器,这将需要进行身份验证,您将添加

finally - as it is written in documentation - in the controller, which will need to be authenticated, you will add

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

您可以创建自定义的中间件如果提供那些不适合您的需求。

You can create a custom middleware if provided ones do not suit your needs.

这篇关于使用Laravel验证的中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 01:10