默认情况下,如果我没有登录,我尝试在浏览器中访问它:
http://localhost:8000/home
Run Code Online (Sandbox Code Playgroud)
它重定向我 http://localhost:8000/auth/login
如何更改以重定向到我 http://localhost:8000/login
Mor*_*ert 40
我想在Laravel 5.5中做同样的事情.处理身份验证已经移动到Illuminate\Auth\Middleware\Authenticate哪个抛出了Illuminate\Auth\AuthenticationException.
处理该异常Illuminate\Foundation\Exceptions\Hander.php,但您不想更改原始供应商文件,因此您可以通过将其添加到自己的项目文件来覆盖它App\Exceptions\Handler.php.
为此,请将以下内容添加到Handler类的顶部App\Exceptions\Handler.php:
use Illuminate\Auth\AuthenticationException;
Run Code Online (Sandbox Code Playgroud)
然后添加以下方法,根据需要进行编辑:
/**
* Convert an authentication exception into an unauthenticated response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest('login'); //<----- Change this
}
Run Code Online (Sandbox Code Playgroud)
只要改变return redirect()->guest('login');对return redirect()->guest(route('auth.login'));或其他任何东西.
我想把它写下来,因为花了我超过5分钟来搞清楚.如果你碰巧在文档中找到这个,请给我留言,因为我做不到.
e1v*_*e1v 31
只是为了延伸@ ultimate的答案:
App\Http\Middleware\Authenticate::handle()方法并更改auth/login为/login.$loginPath在你的\App\Http\Controllers\Auth\AuthController班级添加属性.为什么?请参阅Laravel来源.结果你将在你的中间件中有这个:
namespace App\Http\Middleware;
class Authenticate {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('/login'); // <--- note this
}
}
return $next($request);
}
}
Run Code Online (Sandbox Code Playgroud)
这在您的AuthController中:
namespace App\Http\Controllers\Auth;
class AuthController extends Controller
{
protected $loginPath = '/login'; // <--- note this
// ... other properties, constructor, traits, etc
}
Run Code Online (Sandbox Code Playgroud)
小智 11
这是Laravel 5.4解决方案:
app/Exceptions/Handler.php中有一个新的unauthenticated()方法,它处理未经身份验证的用户并重定向到登录路径.
所以改变
return redirect()->guest('login');
Run Code Online (Sandbox Code Playgroud)
至
return redirect()->guest('auth/login');
Run Code Online (Sandbox Code Playgroud)
身份验证检查是使用 Laravel 5 中的中间件进行的。
auth 的中间件是App\Http\Middleware\Authenticate.
handle因此,您可以在中间件的方法中更改它。
在Laravel 5.6中,转到app / Exceptions文件夹并打开Handler.php,添加一个新方法来覆盖未经身份验证的方法,如下所示:
protected function unauthenticated($request, AuthenticationException $exception)
{
if($request->ajax())
{
return response([
"message" => "Unauthenticated.",
"data" => [],
],401);
}
return redirect()->to('/');
}
Run Code Online (Sandbox Code Playgroud)
当您使用内置的“ auth”中间件访问受保护的路由时,将触发此方法。现在,您将完全控制重定向到何处或发送了响应。