问题描述
我有一个基本的网页,我希望用户能够在其中单击登录链接,完成登录,然后返回到该页面(而不是主页)。该页面有一些只有在用户登录后才能看到的功能。
我遇到了这个问题,无论我何时登录,它都会在身份验证后返回主页,或者我设置为常量的任何内容,而不是前一页。
Fortify.PHP 的主路径是一个常量,所以我也不能用表达式更新它...
'home' => RouteServiceProvider::HOME,
这是中间件 RedirectIfAuthenticated.PHP,它是标准的 Laravel,我想知道需要更新什么。
<?PHP
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null ...$guards
* @return mixed
*/
public function handle(Request $request,Closure $next,...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}
我也应该注意,如果我向页面添加一个中间件路由,如下例所示,那么只要将用户返回到前一个页面,该过程就会正常工作。
Route::middleware(['auth:sanctum','verified'])->get('/agenda',function () {
return view('agenda');
})->name('agenda');
但是,我需要用户能够查看 agenda
页面,即使他们是访客...但是,一旦登录,他们将返回到议程页面,该页面将有一些额外的特征。不幸的是,我似乎在文档中找不到任何关于此的信息。
解决方法
在 AuthenticatesUsers.php
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
if ($response = $this->authenticated($request,$this->guard()->user())) {
return $response;
}
return $request->wantsJson()
? new JsonResponse([],204)
: redirect()->back();
}
或者您可以在第 31 行的默认登录控制器中执行此操作
protected $redirectTo = "/your-path";
,
当 auth 中间件检测到未经身份验证的用户时,它会将用户重定向到名为 route 的登录名。您可以通过更新应用程序 app/Http/Middleware/Authenticate.php
文件中的 redirectTo 函数来修改此行为
https://laravel.com/docs/8.x/authentication#redirecting-unauthenticated-users