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');
,我都会不断收到此错误:标题可能不只包含一个标题,而且已检测到新行。有关如何解决此问题的任何想法?
答案 0 :(得分:1)
根据@ ourmandave和[https://laracasts.com/discuss/channels/laravel/method-redirectto-with-a-flash-message][2]的建议,我了解到redirectTo()希望返回重定向路由名称,而不是实际重定向。因此,您应该将“消息”刷新到您的会话中,然后返回重定向“ /登录”。因此,我将代码编辑为如下所示,现在可以正常工作了:
this.myForm= this.builder.group({
myDate: [this.todayDateToMyDatePicker()]
})