Laravel的Authenticate
中间件获取用户在未经过身份验证时应重定向到的路径,默认情况下会将用户重定向到/login
。我想实现一个添加的功能,用一个消息重定向用户(例如XYZ分钟的会话时间到期或亲切登录继续)。所以我的Authenticate
中间件看起来像这样:
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Exceptions\HttpResponseException;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function redirectTo($request)
{
if($request->is('api/*'))
{
throw new HttpResponseException(response()->error(['failure_reason'=>'Fresh Access Token Required'], 'Unauthorized Request', 401));
}
if (!$request->expectsJson()) {
// return route('login');
$request->headers->set('Accept', 'application/json');
return redirect("/login")->with("message", "Exceeded an inactivity period of over 15 mins. Kindly re-login to continue");
}
}
}
有或没有$request->headers->set('Accept', 'application/json');
,我不断收到此错误:标题可能不包含多个标题,检测到新行。关于如何解决这个问题的任何想法?
根据@ourmandave和[https://laracasts.com/discuss/channels/laravel/method-redirectto-with-a-flash-message][2]的建议,我了解到redirectTo()想要返回重定向路由名称,而不是实际重定向。因此,您应该将“消息”闪烁到您的会话,然后返回重定向'/ login'。所以我编辑了我的代码,如下所示,它现在有效:
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Exceptions\HttpResponseException;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function redirectTo($request)
{
if($request->is('api/*'))
{
throw new HttpResponseException(response()->error(['failure_reason'=>'Fresh Access Token Required'], 'Unauthorized Request', 401));
}
if (!$request->expectsJson()) {
session()->flash('message', 'Exceeded an inactivity period of over 15 mins. Kindly re-login to continue');
return route('login');
}
}
}