Laravel:具有相同路由的多个身份验证

时间:2019-09-15 17:16:49

标签: laravel authentication routes

我有一个Laravel(5.8)应用程序,其中有两个角色Super AdminAdmin,分别保存在两个不同的表adminsusers中。它们每个都有各自的访问级别。但是,整个应用程序中大约95%的路由对于每个路由都是相同的,但是会根据其访问级别进行限制或修改。

例如:
Admin只能更新自己的个人资料,并具有创建和查看的权限。
Super Admin可以查看和播放admins的列表,并具有创建/更新/查看和删除的权限。

因此,我有两个后卫users(default) = users tableadmins = admins table。但是,当我在同一个控制器中同时添加这两个或守护者时,它只会不断重定向并显示the page is not redirecting properly

config / auth.php

'guards' => [
    'web' => [
        'driver'   => 'session',
        'provider' => 'users',
    ],

    'member' => [
        'driver'   => 'session',
        'provider' => 'member',
    ],
    ...
],
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model'  => App\User::class,
    ],

    'member' => [
        'driver' => 'eloquent',
        'model'  => App\Member::class,
    ],
],

User.php

class User extends Authenticatable
{
    ...

    public function _login($request)
    {
        if(\Auth::attempt([
            'email'    => $request->email,
            'password' => $request->password
        ]))
        {
            return [
                'success' => true
            ];
        }
        else
        {
            return [
                'success' => false
            ];
        }
    }
}

Member.php

class Member extends Authenticatable
{
    ...

    public function _login($request)
    {
        if(\Auth::guard('member')->attempt([
            'email'    => $request->email,
            'password' => $request->password
        ]))
        {
            return [
                'success' => true
            ];
        }
        else
        {
            return [
                'success' => false
            ];
        }
    }
}

HomeController.php

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        echo "<pre>";

        if(\Auth::user())
        {
            print_r(\Auth::user());
        }
        else if(\Auth::guard('member')->user())
        {
            print_r(\Auth::guard('member')->user());
        }

        echo "</pre>";
    }
}

如果我在auth中评论了__construct()中间件,那么它将起作用并显示已登录用户的数据,但是如果继续重定向并显示the page is not redirecting properly错误。

1 个答案:

答案 0 :(得分:0)

您可能想使用$this->middleware('auth:web')$this->middleware('auth:member'),以便您的中间件知道要使用哪种防护。

:之后的所有内容作为参数传递给中间件的handle()函数。