保护页面 - Laravel

时间:2015-12-27 06:52:07

标签: php laravel laravel-5

在旧式php中,如果我出于某种原因想要阻止访问页面(不一定是身份验证),我会使用下面的代码;

if (!isset($_GET["token"])) {
    header("Location: password-link-invalid.html");
    exit;
}

if (!isset($_GET["timestamp"])) {
    header("Location: password-link-invalid.html");
    exit;
}

if ($_SERVER["REQUEST_TIME"] - $timestamp > 3600)
{
    header("Location: password-link-expired.html");
    exit;
}

我如何在Laravel中实现这一目标?

由于

1 个答案:

答案 0 :(得分:4)

只需创建自己的中间件并将它们分配给您想要保护的路线:

<?php

namespace App\Http\Middleware;

use Closure;

class TokenDateCheckerMiddleware
{
    /**
     * Run the request filter.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if (is_null($request->input('token')) ||
            is_null($request->input('timestamp'))) {

            return redirect('password-link-invalid.html');
        }

        return $next($request);
    }

}

然后你需要在内核中分配这个中间件:(来自docs)

如果您希望在对应用程序的每个HTTP请求期间运行中间件,只需在app / Http / Kernel.php类的$ middleware属性中列出中间件类。

// Within App\Http\Kernel Class...

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'tokenDateCheck' => \App\Http\Middleware\TokenDateCheckerMiddleware::class,
];

然后,您将i分配给所需的特定网址:

Route::get('admin/profile', ['middleware' => 'tokenDateCheck', function () {
    //
}]);

你可以在这里阅读所有相关内容: https://laravel.com/docs/5.2/middleware#defining-middleware