Php 用户登录后,Laravel自定义防护不工作
我有一个自定义登录控制器,用于根据用户访问级别设置自定义防护,这将决定他们可以在站点上访问什么 登录可以工作,但是当我添加中间件来保护路由时,它返回null,我不确定这是基于用户登录设置防护的正确方法 目前,代码只是循环回到登录页面,而自定义保护返回nullPhp 用户登录后,Laravel自定义防护不工作,php,laravel,routes,Php,Laravel,Routes,我有一个自定义登录控制器,用于根据用户访问级别设置自定义防护,这将决定他们可以在站点上访问什么 登录可以工作,但是当我添加中间件来保护路由时,它返回null,我不确定这是基于用户登录设置防护的正确方法 目前,代码只是循环回到登录页面,而自定义保护返回null // loginController.php if (Auth::attempt($request->only('email', 'password'))) { Auth::login(Auth::user(
// 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');
}
*更新*
我解决了这个问题,因为我正在设置安全cookies,但是在本地环境中工作。这两种解决方案都有效,只需要一个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');
}
登录控制器中的
Auth::trunt
和Auth::login
将使用config/Auth.php
中定义的默认保护。您必须指定他们应该使用的防护装置
而您的$this->guard('custom_user')
本身不会做任何事情,因为它只返回一个Auth实例
将默认防护更改为custom\u user
,或在控制器中更改此选项:
if ($this->guard('custom_user')->attempt($request->only('email', 'password'))) {
$this->guard('custom_user')->login(Auth::user(), true);
return redirect('/home');
}
你所描述的听起来像是授权而不是认证,所以问题似乎出在中间件上。当我实现这段代码时,执行
dd(Auth::guard()->check())代码>它返回true,然后一旦它命中中间件,相同的检查就会返回false。