What is the best way to restrict access in Laravel?

╄→尐↘猪︶ㄣ 提交于 2021-02-08 11:02:14

问题


I am designing a website where only logged in user can access the content of some parts of the site.So which of the following method is more secure and a industry standard?

Method 1: Checking if the user is logged in and doing something like the following in a view:

@if (Auth::check())
   // content for logged in user
@else
   // Access restricted warning message for guests
@endif

Method 2: Using the route technique

Route::get('study',array('before'=>'auth','uses'=>'home@study'));

And there is no point in using both techniques simultaneously,right?


回答1:


Use filters in your router. As codenamegary is suggesting, use a filter. That's common practice and very explicit.

A filter example:

Route::group(array('before' => 'auth'), function()
{
    Route::controller('backend.index');
    Route::controller('backend.dashboard');
}

And the filter definition:

Route::filter('auth', function()
{
    if (Auth::guest()) return Redirect::to('login');
});



回答2:


In this scenario most definitely use a filter, that's exactly what they were designed for.

The next level of granularity you'll probably run up against is restricting access to crud operations based on the permissions of the logged in user. In that scenario consider filters with some type of RBAC implementation, there is a great bundle called Authority that helps you do this.

Also don't forget that best practice would be to return a 403 when the user is denied access from a filter rather than a 200.

Beyond that you'll probably get into nesting different content into your views based on the permissions of the logged in user, for that I typically find a combination of RBAC and view composers works very well.

Don't forget that you can apply filters inside your controller's constructor as well as at the route level, I often find this is more consistent and reliable but both are good methods.

http://www.laravel.com/docs/controllers#action-filters




回答3:


Both are secure and can be used complementarily.

Blog example :

In routes

// Secure the edit post
Route::get('blog/edit',array('before'=>'auth','uses'=>'blog@getEdit')); 
// Display a post
Route::get('blog/read/{id}', 'blog@getRead'));

In 'Display a post' view :

@if (Auth::check())
   // display edit link
@endif


来源:https://stackoverflow.com/questions/16262727/what-is-the-best-way-to-restrict-access-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!