【问题标题】:Laravel 5.2 Error In Custom AuthenticationLaravel 5.2 自定义身份验证错误
【发布时间】:2016-05-28 22:19:08
【问题描述】:

我在为我的 laravel 5.2 进行自定义身份验证时遇到错误,但是此代码在我的 laravel 5.1 我的 config/auth.php 文件上运行良好

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

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

我的 CustomUserProvider.php (Auth/CustomUserProvider) 文件

    <?php namespace App\Auth;

use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class CustomUserProvider implements UserProvider {

    protected $model;

    public function __construct(UserContract $model)
    {
        $this->model = $model;
    }

    public function retrieveById($identifier)
    {

    }

    public function retrieveByToken($identifier, $token)
    {

    }

    public function updateRememberToken(UserContract $user, $token)
    {

    }

    public function retrieveByCredentials(array $credentials)
    {

    }

    public function validateCredentials(UserContract $user, array $credentials)
    {

    }

}

我的 CustomAuthProvider.php 文件

    <?php namespace App\Providers;

use App\User;
use Auth;
use App\Auth\CustomUserProvider;
use Illuminate\Support\ServiceProvider;

class CustomAuthProvider extends ServiceProvider {

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->app['auth']->extend('custom',function()
        {

            return new CustomUserProvider();
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

}

现在这在 5.2 中的 laravel 5.1 中可以正常工作,我收到类似

的错误
InvalidArgumentException in CreatesUserProviders.php line 40:
Authentication user provider [custom] is not defined.

【问题讨论】:

  • 我认为在启动方法中,您必须使用 App::provider 向应用程序注册您的自定义用户提供程序。您使用的方式是做同样事情的替代方式吗?
  • 查看文档以获取更多详细信息。 laravel.com/docs/5.2/…
  • @AlankarMore 我已经注册了我的服务提供商并自动加载了文件
  • 尝试将'driver' =&gt; 'custom',更改为'driver' =&gt; 'customUser',将$this-&gt;app['auth']-&gt;extend('custom',function()更改为$this-&gt;app['auth']-&gt;extend('customUser',function()
  • InvalidArgumentException in CreatesUserProviders.php 第 40 行:未定义身份验证用户提供程序 [customUser]。

标签: php laravel laravel-5.2 service-provider


【解决方案1】:

尝试如下替换开机功能:

public function boot()
{
    Auth::provider('custom', function($app, array $config) {
        // Return an instance of Illuminate\Contracts\Auth\UserProvider...
        return new CustomUserProvider($app['custom.connection']);
    });
}

【讨论】:

  • 我一直在尝试像 $this->app['auth'] 一样的东西,但不工作顺便说一句 custom.connection 代表我在 php 中的意思。 ?
  • 我认为它可能会返回您的自定义用户提供程序的连接。因此,无论您在自定义用户提供程序驱动程序中使用了什么模型,该模型实例都将由此 custom.connection 返回。我不确定是否需要深入研究 Laravel API 文档。您的 UserContract 模型是否扩展到了用户模型?
【解决方案2】:

app/Models/User.php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable {
protected $connection='conn';
protected $table='users-custom';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'login', 'passwd'
];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = [
    'passwd',
];

public function getAuthPassword(){
    //your passwor field name
    return $this->passwd;
}

public $timestamps = false;

}

创建应用程序/Auth/CustomUserProvider.php

 namespace App\Auth;

use Illuminate\Support\Str;

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

/**
 * Description of CustomUserProvider
 *
 */

class CustomUserProvider implements UserProvider {

/**
 * The hasher implementation.
 *
 * @var \Illuminate\Contracts\Hashing\Hasher
 */
protected $hasher;

/**
 * The Eloquent user model.
 *
 * @var string
 */
protected $model;

/**
 * Create a new database user provider.
 *
 * @param  \Illuminate\Contracts\Hashing\Hasher  $hasher
 * @param  string  $model class name of model
 * @return void
 */
public function __construct($model) {
    $this->model = $model;        
}

/**
 * Retrieve a user by their unique identifier.
 *
 * @param  mixed  $identifier
 * @return \Illuminate\Contracts\Auth\Authenticatable|null
 */
public function retrieveById($identifier) {
    return $this->createModel()->newQuery()->find($identifier);
}

/**
 * Retrieve a user by their unique identifier and "remember me" token.
 *
 * @param  mixed  $identifier
 * @param  string  $token
 * @return \Illuminate\Contracts\Auth\Authenticatable|null
 */
public function retrieveByToken($identifier, $token) {
    $model = $this->createModel();

    return $model->newQuery()
                    ->where($model->getAuthIdentifierName(), $identifier)
                    ->where($model->getRememberTokenName(), $token)
                    ->first();
}

/**
 * Update the "remember me" token for the given user in storage.
 *
 * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
 * @param  string  $token
 * @return void
 */
public function updateRememberToken(UserContract $user, $token) {
    $user->setRememberToken($token);

    $user->save();
}

/**
 * Retrieve a user by the given credentials.
 *
 * @param  array  $credentials
 * @return \Illuminate\Contracts\Auth\Authenticatable|null
 */
public function retrieveByCredentials(array $credentials) {
    // First we will add each credential element to the query as a where clause.
    // Then we can execute the query and, if we found a user, return it in a
    // Eloquent User "model" that will be utilized by the Guard instances.
    $query = $this->createModel()->newQuery();

    foreach ($credentials as $key => $value) {            
        if (!Str::contains($key, 'password')) {
            $query->where($key, $value);
        }
    }

    return $query->first();
}

/**
 * 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) {
//your method auth
        $plain = $credentials['password'];
        return  md5($plain)==md5($user->getAuthPassword());
    }

/**
 * Create a new instance of the model.
 *
 * @return \Illuminate\Database\Eloquent\Model
 */
public function createModel() {
    $class = '\\' . ltrim($this->model, '\\');
    return new $class;
}

/**
 * Gets the hasher implementation.
 *
 * @return \Illuminate\Contracts\Hashing\Hasher
 */
public function getHasher() {
    return $this->hasher;
}

/**
 * Sets the hasher implementation.
 *
 * @param  \Illuminate\Contracts\Hashing\Hasher  $hasher
 * @return $this
 */
public function setHasher(HasherContract $hasher) {
    $this->hasher = $hasher;

    return $this;
}

/**
 * Gets the name of the Eloquent user model.
 *
 * @return string
 */
public function getModel() {
    return $this->model;
}

/**
 * Sets the name of the Eloquent user model.
 *
 * @param  string  $model
 * @return $this
 */
public function setModel($model) {
    $this->model = $model;

    return $this;
}

}

在 config/auth.php 中

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


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


'users_office' => [
        'driver' => 'customUser',
        'model' => App\Models\User::class,
    ],
// 'users' => [
//     'driver' => 'database',
//     'table' => 'users',
// ],
],

在 \vendor\laravel\framework\src\Illuminate\AuthCreatesUserProviders.php 中

 public function createUserProvider($provider)
{
    $config = $this->app['config']['auth.providers.'.$provider];    


    if (isset($this->customProviderCreators[$config['driver']])) {
        return call_user_func(
            $this->customProviderCreators[$config['driver']], $this->app, $config
        );
    }

    switch ($config['driver']) {
        case 'database':
            return $this->createDatabaseProvider($config);
        case 'eloquent':
            return $this->createEloquentProvider($config);
        case 'customUser':
            return $this->createCustomUserProvider($config);
        default:
            throw new InvalidArgumentException("Authentication user provider [{$config['driver']}] is not defined.");
    }
}


protected function createCustomUserProvider($config){        
        return new \App\Auth\CustomUserProvider($config['model']);
    }

添加 App\Providers\CustomUserAuthProvider.php

    namespace App\Providers;

use Auth;
use App\Models\User;
use App\Auth\CustomUserProvider;
use Illuminate\Support\ServiceProvider;

/**
 * Description of CustomAuthProvider
 *
 */

class CustomUserAuthProvider extends ServiceProvider {

/**
 * Bootstrap the application services.
 *
 * @return void
 */
public function boot()
{        
     Auth::extend('customUser', function($app) {
        // Return an instance of Illuminate\Contracts\Auth\UserProvider...
        return new CustomUserProvider(new User);
    });
}

/**
 * Register the application services.
 *
 * @return void
 */
public function register()
{
    //
}

}

【讨论】:

  • 这是一个解决方案,但它太脏了。我可行的解决方案不应包括框架本身的更改,尤其是供应商文件夹,或者框架已损坏。在 4.2 中,它可以以一种干净的方式实现,我相信必须有一种方法可以将自定义创建者注册到 CreatesUserProviders$customProviderCreators 属性中。
【解决方案3】:

替换开机功能如下:

public function boot()
    {
        Auth::provider('customUser', function($app, array $config) {
            return new CustomUserProvider($config['model']);
        });
    }

【讨论】:

    【解决方案4】:

    唯一的一点就是使用

    $this->app['auth']->provider(... 
    

    而不是

    $this->app['auth']->extend(...
    

    5.1用最后一个,5.2应该用第一个。

    【讨论】:

      猜你喜欢
      • 2016-04-18
      • 2017-01-20
      • 2016-09-15
      • 2015-02-23
      • 2014-03-30
      • 1970-01-01
      • 2018-11-22
      • 2016-07-09
      相关资源
      最近更新 更多