更改登录路由

  • 本文关键字:路由 登录 laravel
  • 更新时间 :
  • 英文 :


我在Laravel auth应用程序中工作,当我的用户注销时,我想将其重定向到自定义静态页面,然后单击该页面上的按钮再次重定向到登录页面。例如,当用户试图访问某个特定的路由,而他未经授权时,我想用satatic.blade.php重定向,然后从那里我想将其重定向到登录页面,我该如何实现?

由于您没有提到您正在使用哪个Laravel版本和使用哪个脚手架,我假设您正在使用带有LaravelUI/default auth scaffolding的Laravel 5.5/6。

您应该有App\Http\Controllers\Auth命名空间,在其中保存所有与身份验证相关的控制器。

您应该有一个LoginController.php,它包含AuthenticatesUsers特征中的所有默认登录行为。我们应该重写控制器中的登录方法。

将此代码复制到您的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生成一个中间件,并在你的路由中使用它。

CheckResourceAccessMiddlewarehandle方法中

// 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' => AppHttpMiddlewareCheckResourceAccessMiddleware::class,
];

在该步骤之后。,您可以在任何想要保护的路由中使用中间件

Route::get('/protected', [Controller::class, 'method'])->middleware('resource_access');


// Middleware will be applied to all routes inside it
Route::middleware('resource_access')->group(function () {
Route::get('/protected', [Controller::class, 'method']);
// all other protected routes will be here
});

我找到了解决这个问题的不同方法,后来我找到了最好的解决方案,如下所述,

在App\Middlewear\Authenticate.php中,我必须更改返回路由("登录"(;返回路由('my_custom_page_route'(;从我的自定义页面,我可以很容易地将其重定向到身份验证登录页面。

感谢所有提出最佳解决方案的人。

最新更新