我正在为我的项目使用 Larave 5。在我的项目中,我正在使用 laravel 默认身份验证,它使用此命令php artisan make:auth
.我在路由中设置了中间件.php如图所示
Route::group(['middleware' => 'web'], function () {
// Authentication Routes...
Route::auth();
Route::get('/', 'AuthAuthController@getLogin');
Route::post('auth/login', 'AuthAuthController@postLogin');
Route::get('auth/logout', 'AuthAuthController@getLogout');
// Admin Roles Routes...
Route::get('admin/roles', 'AdminController@showRoles');
});
现在我的问题是,如果我的用户正在注销并单击浏览器后退按钮用户登录,用户可以在注销后访问添加、编辑、删除视图。那么我该如何处理这种情况。请帮助我认为我错过了一些代码。
首先,您的 Route::auth() 已经具有登录和注销功能,如果您在终端中运行 'php artisan route:list',您可以看到哪些路由可用等。
其次,您可以为管理员创建如下所示的组:
Route::group(['middleware' => 'web'], function () {
// Authentication Routes...
Route::auth();
// Admin Roles Routes...
Route::group(['prefix'=>'admin', 'middleware'=>'auth'], function() {
Route::get('roles', 'AdminController@showRoles');
});
});
我希望这对你有用;)
顺便说一句,Laravel文档告诉你很多......,所以一定要先看它们;)
首先,您不需要应用web
中间件,因为它已经通过RouteServiceProvider
应用于您的路由,请参阅 https://laravel.com/docs/5.2/middleware#registering-middleware
其次,当使用Route:auth()
它是以下方面的快捷方式:
$this->get('login', 'AuthAuthController@showLoginForm');
$this->post('login', 'AuthAuthController@login');
$this->get('logout', 'AuthAuthController@logout');
$this->get('register', 'AuthAuthController@showRegistrationForm');
$this->post('register', 'AuthAuthController@register');
$this->get('password/reset/{token?}', 'AuthPasswordController@showResetForm');
$this->post('password/email', 'AuthPasswordController@sendResetLinkEmail');
$this->post('password/reset', 'AuthPasswordController@reset');
因此,您无需定义这些路由:
Route::post('auth/login', 'AuthAuthController@postLogin');
Route::get('auth/logout', 'AuthAuthController@getLogout');
最后,为什么要在主页上登录?
Route::get('/', 'AuthAuthController@getLogin');
这个例子应该是工作:
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
return 'Hello! You are logged in.';
});
// Admin Roles Routes...
Route::get('admin/roles', 'AdminController@showRoles');
});
Route::auth();
使用上述路由,当未经身份验证的用户尝试访问您的主页时http://yoursite.com
并http://yoursite.com/admin/roles
,用户将被重定向到http://yoursite.com/login
,因为这些页面受auth
中间件保护。
@Rick答案的补充。
您也可以在控制器的 __construct() 函数中手动设置中间件。
例:
// SomeController.php
public function __construct()
{
$this->middleware('auth');
}
文档