自定义登陆
重写登陆页面和登陆逻辑
方式一,重写登陆控制器方法:
默认的登陆控制器用的是App\Admin\AuthController这个类,可以通过配置参数admin.auth.controller进行修改
<?phpnamespace App\Admin\Controllers;use Dcat\Admin\Controllers\AuthController as BaseAuthController;class AuthController extends BaseAuthController{// 自定义登陆view模板protected $view = 'admin.login';// 重写你的登陆页面逻辑public function getLogin(Content $content){...}...}
方式二,覆写路由:
在路由文件app/Admin/routes.php中,覆盖掉登陆页面和登陆逻辑的路由,即可实现自定义的功能
Route::group(['prefix' => config('admin.prefix'),'namespace' => Admin::controllerNamespace(),'middleware' => ['web', 'admin'],], function (Router $router) {$router->get('auth/login', 'AuthController@getLogin');$router->post('auth/login', 'AuthController@postLogin');});
在自定义的路由器AuthController中的getLogin、postLogin方法里分别实现自己的登陆页面和登陆逻辑。
重写laravel认证
如果不使用Dcat Admin内置的认证登陆逻辑,可以参考下面的方式自定义登陆认证逻辑
首先要先定义一个user provider,用来获取用户身份, 比如app/Providers/CustomUserProvider.php:
<?phpnamespace App\Providers;use Illuminate\Contracts\Auth\Authenticatable;use Illuminate\Contracts\Auth\UserProvider;class CustomUserProvider implements UserProvider{public function retrieveById($identifier){}public function retrieveByToken($identifier, $token){}public function updateRememberToken(Authenticatable $user, $token){}public function retrieveByCredentials(array $credentials){// 用$credentials里面的用户名密码去获取用户信息,然后返回Illuminate\Contracts\Auth\Authenticatable对象}public function validateCredentials(Authenticatable $user, array $credentials){// 用$credentials里面的用户名密码校验用户,返回true或false}}
在方法retrieveByCredentials和validateCredentials中, 传入的$credentials就是登陆页面提交的用户名和密码数组,然后你可以使用$credentials去实现自己的登陆逻辑
Interface Illuminate\Contracts\Auth\Authenticatable的定义如下:
<?phpnamespace Illuminate\Contracts\Auth;interface Authenticatable {public function getAuthIdentifierName();public function getAuthIdentifier();public function getAuthPassword();public function getRememberToken();public function setRememberToken($value);public function getRememberTokenName();}
上面interface每个方法的解释参考adding-custom-user-providers
定义好了User provider之后,打开app/Providers/AuthServiceProvider.php注册它:
<?phpnamespace App\Providers;use Illuminate\Support\Facades\Auth;use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;class AuthServiceProvider extends ServiceProvider{/*** Register any application authentication / authorization services.** @return void*/public function boot(){$this->registerPolicies();Auth::provider('custom', function ($app, array $config) {// Return an instance of Illuminate\Contracts\Auth\UserProvider...return new CustomUserProvider();});}}
最后修改一下配置,打开config/admin.php,找到auth部分修改:
'auth' => ['guards' => ['admin' => ['driver' => 'session','provider' => 'admin',]],// 修改下面'providers' => ['admin' => ['driver' => 'custom',]],],
这样就完成了自定义登陆认证的逻辑,自定义登陆算是laravel中比较复杂的部分,需要开发者有耐心的一步步调试完成。
