我在 Laravel 身份验证应用程序中工作,当我的用户注销时,我想将其重定向到自定义静态页面,然后我想通过单击该页面上的按钮再次重定向到登录页面。 例如,当用户尝试访问某个特定的路由,而他未经授权时,我想使用 satatic.blade.php 进行重定向,然后我想将其重定向到登录页面,我该如何实现?
答案 0 :(得分:0)
由于您没有提到您使用的是哪个 Laravel 版本以及您使用的是哪个脚手架,我假设您使用的是带有 LaravelUI/默认身份验证脚手架的 Laravel 5.5/6。
您应该拥有 App\\Http\\Controllers\\Auth
命名空间,其中保存了所有与身份验证相关的控制器。
您应该有一个 LoginController.php
,其中包含 AuthenticatesUsers
特征内的所有默认登录行为。我们应该覆盖控制器中的 login 方法。
将此代码复制到您的 LoginController
类以执行此操作。
public function login(Request $request)
{
$this->validateLogin($request);
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
// Here is our custom logic check occurs before login
if ($this->userIsnotAuthorized()) { // All your logic checks are inside 'userIsnotAuthorized()' method. Use any function or static check here
return redirect()->to('/static/page'); // Also can use route name / url
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
编辑 #1
如果您想对所有受保护的路由进行相同的检查,您应该使用 php artisan make:middleware CheckResourceAccessMiddleware
生成一个中间件,并在您的路由中使用相同的内容。
在CheckResourceAccessMiddleware
的{{1}}方法中
handle
要注册中间件,请编辑您的 // Here is our custom logic check occurs before login
if ($this->userIsnotAuthorized()) { // All your logic checks are inside 'userIsnotAuthorized()' method. Use any function or static check here
return redirect()->to('/static/page'); // redirect to static page which indicates unauthorized user note
}
return $next($request); // proceed to your page as user is authorized
并将此行添加到 app/Http/Kernel.php
数组
$routeMiddleware
这一步之后,你可以在任何你想要保护的路由中使用中间件
protected $routeMiddleware = [
...
'resource_access' => \App\Http\Middleware\CheckResourceAccessMiddleware::class,
];
或
Route::get('/protected', [Controller::class, 'method'])->middleware('resource_access');
答案 1 :(得分:0)
我找到了解决这个问题的不同方法,后来我找到了最好的解决方案,如下所述,
在 App\Middlewear\Authenticate.php 中,我必须从 return route('login'); 返回路线('my_custom_page_route'); 从我的自定义页面,我可以轻松地将其重定向到身份验证登录页面。
感谢所有提出最佳解决方案的人。