You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.6自定义User Provider添加权限校验遇驱动配置异常

解决Laravel 5.6自定义用户提供者驱动报错的问题

我之前也碰到过一模一样的问题——Laravel的Auth组件对用户提供者的驱动有严格的白名单校验,直接在config/auth.php里改驱动名称肯定会触发那个异常,因为它默认只认eloquent和database这俩。下面是我当时搞定这个需求的完整步骤:

1. 创建自定义用户提供者类

先新建一个自定义的用户提供者,继承Laravel自带的EloquentUserProvider,这样我们只需要重写validateCredentials方法,其他逻辑复用默认的就好。

在app/Auth目录下创建CustomUserProvider.php(如果没有Auth目录就自己建一个):

<?php

namespace App\Auth;

use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class CustomUserProvider extends EloquentUserProvider
{
    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        // 先验证账号密码是否正确
        $isValidCredentials = parent::validateCredentials($user, $credentials);
        
        if (!$isValidCredentials) {
            return false;
        }
        
        // 这里加入你的权限校验逻辑,根据laravel-permissions的用法调整
        // 举个例子:检查用户是否有访问后台的权限
        return $user->hasPermissionTo('access-admin');
    }
}

2. 注册自定义用户提供者驱动

接下来要告诉Laravel我们的自定义驱动存在,打开app/Providers/AuthServiceProvider.php,在boot方法里注册这个驱动:

<?php

namespace App\Providers;

use App\Auth\CustomUserProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    // ... 其他代码

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        // 注册自定义用户提供者驱动
        Auth::provider('custom_eloquent', function ($app, array $config) {
            return new CustomUserProvider($app['hash'], $config['model']);
        });
    }
}

3. 修改Auth配置文件

最后修改config/auth.php,把web守卫的提供者换成我们自定义的驱动:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'custom_users', // 这里改成自定义的提供者名称
    ],

    // ... 其他守卫
],

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

    // 新增自定义的提供者
    'custom_users' => [
        'driver' => 'custom_eloquent', // 这里是我们注册的驱动名
        'model' => App\User::class,
    ],
],

为什么之前会报错?

你碰到的那个异常来自Illuminate/Auth/CreatesUserProviders.php的第24行,那里有个校验逻辑:只有当驱动在['eloquent', 'database']这个白名单里时,才会创建对应的用户提供者。所以我们必须通过Auth::provider()方法注册自己的驱动,让Laravel识别它,才能正常使用。

另外要注意:权限校验的逻辑要根据你的实际需求调整,比如如果是要校验路由权限,也可以考虑用中间件的方式(比如laravel-permissions自带的permission中间件),这种方式可能比在用户提供者里校验更灵活,你可以根据场景选择~

内容的提问来源于stack exchange,提问作者jwtea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:51:53