[英]Laravel 8 custom logout method not working and not logs out the user
[英]Laravel custom guard not working once user logs in
我有一个自定义登录控制器,该控制器旨在根据用户访问级别设置自定义防护,这将决定他们可以在站点上访问的内容。
登录有效,但是当我添加中间件来保护路由时,它将返回null,并且我不确定这是否是基于用户登录设置防护的正确方法。
当前,代码仅循环回到登录页面,而自定义防护返回null。
// loginController.php
if (Auth::attempt($request->only('email', 'password'))) {
Auth::login(Auth::user(), true);
$this->guard('custom_user');
return redirect('/home');
}
protected function guard($custom_user){
return Auth::guard($custom_user);
}
// config/auth.php
'guards' => [
'custom_user' => [
'driver' => 'session',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
],
// middleware/RedirectIfAuthenticaed.php
public function handle($request, Closure $next)
{
if (Auth::guard('custom_user')->check()) {
return $next($request);
}
return redirect('/login');
}
*更新*
我解决了这个问题,是因为我正在设置安全的Cookie,但是在本地环境中工作。 两种解决方案都有效,只需要一个SSL。
在您的LoginController中
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/home';
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('custom_user')->attempt(['email' => $request->email, 'password' => $request->password])) {
return redirect('/home');
}else{
return redirect('/login');
}
}
}
在中间件/RedirectIfAuthenticated.php中
public function handle($request, Closure $next)
{
if (Auth::guard('custom_user')->check()) {
return $next('/home');
}
return redirect('/login');
}
LoginController中的Auth::attempt
和Auth::login
将使用config/auth.php
定义的默认防护。 您必须指定他们应该使用哪个防护。
您的$this->guard('custom_user')
本身不会执行任何操作,因为它仅返回Auth实例。
将默认防护更改为custom_user
或在Controller中进行更改:
if ($this->guard('custom_user')->attempt($request->only('email', 'password'))) {
$this->guard('custom_user')->login(Auth::user(), true);
return redirect('/home');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.