简体   繁体   English

保护Laravel 5.1中的路线

[英]Protect routes in Laravel 5.1

I am using Laravel 5.1 for my project. 我在项目中使用Laravel 5.1。 I am trying to secure Routes and make sure only logged in user can access certain routes. 我正在尝试保护路由,并确保只有登录的用户才能访问某些路由。 I am aware about middlewares but I am wondering if anyone post an example or a link explaining about middleware and how to protect a page using middleware. 我知道中间件,但是我想知道是否有人发布了有关中间件以及如何使用中间件保护页面的示例或链接。

Thanks 谢谢

You are correct about using middleware. 您对使用中间件是正确的。 The included Auth middleware is what you should use, as long as you are also using the included Auth controller to authenticate users. 只要您还使用附带的Auth控制器来验证用户身份,就应该使用附带的Auth中间件。 You would write your route like this: 您将这样编写路线:

Route::get('/page', array(
    'uses' => 'Controller@method',
    'middleware'=>'auth'
));

(The above example is using a GET request, but it could other request types, like POST for example). (以上示例使用的是GET请求,但也可以使用其他请求类型,例如POST )。

This will use the default behavior of the middleware which checks to see if the user is logged in (authenticated). 这将使用中间件的默认行为,该行为检查用户是否已登录(已验证)。 You can also extend or overwrite the built-in functions to allow you to direct the application on where to send the user if they are or are not logged in, etc. Laravel's official documentation is a good starting point: link 您还可以扩展或覆盖内置函数,以使您可以直接将应用程序定向到将用户发送到何处(无论用户是否登录),等等。Laravel的官方文档是一个很好的起点: 链接

To build on the answer given by Joe Rose, you can also specify the middleware in your controller rather than in your routes.php file. 要以Joe Rose给出的答案为基础,还可以在控制器中而不是routes.php文件中指定中间件。

Eg you could have your routes set out like 例如,您可以将路线设置为

Route::get('/example', 'ExampleController@index');
Route::post('/example/post', 'ExampleController@post');
Route::resource('blog', 'BlogController');

And then inside your controller reference it like so: 然后在您的控制器内部引用它,如下所示:

class ExampleController extends Controller
{
    public function __construct()
        {
            $this->middleware('auth');
        }
    //....

If you're looking for more info, check out the link to the docs Joe gave, and also this blog post which explains what middleware is really well and how to create your own if you need to. 如果您正在寻找更多信息,请查看Joe提供的文档的链接,以及此博客文章 ,其中解释了哪种中间件确实很好,以及在需要时如何创建自己的中间件。

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

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