自定义登陆

如果不使用laravel-admin内置的认证登陆逻辑,可以参考下面的方式自定义登陆认证逻辑

首先要先定义一个user provider,用来获取用户身份, 比如app/Providers/CustomUserProvider.php

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Contracts\Auth\Authenticatable;
  4. use Illuminate\Contracts\Auth\UserProvider;
  5. class CustomUserProvider implements UserProvider
  6. {
  7. public function retrieveById($identifier)
  8. {}
  9. public function retrieveByToken($identifier, $token)
  10. {}
  11. public function updateRememberToken(Authenticatable $user, $token)
  12. {}
  13. public function retrieveByCredentials(array $credentials)
  14. {
  15. // 用$credentials里面的用户名密码去获取用户信息,然后返回Illuminate\Contracts\Auth\Authenticatable对象
  16. }
  17. public function validateCredentials(Authenticatable $user, array $credentials)
  18. {
  19. // 用$credentials里面的用户名密码校验用户,返回true或false
  20. }
  21. }

在方法retrieveByCredentialsvalidateCredentials中, 传入的$credentials就是登陆页面提交的用户名和密码数组,然后你可以使用$credentials去实现自己的登陆逻辑

Interface Illuminate\Contracts\Auth\Authenticatable的定义如下:

  1. <?php
  2. namespace Illuminate\Contracts\Auth;
  3. interface Authenticatable {
  4. public function getAuthIdentifierName();
  5. public function getAuthIdentifier();
  6. public function getAuthPassword();
  7. public function getRememberToken();
  8. public function setRememberToken($value);
  9. public function getRememberTokenName();
  10. }

上面interface每个方法的解释参考adding-custom-user-providers

定义好了User provider之后,打开app/Providers/AuthServiceProvider.php注册它:

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\Facades\Auth;
  4. use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
  5. class AuthServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Register any application authentication / authorization services.
  9. *
  10. * @return void
  11. */
  12. public function boot()
  13. {
  14. $this->registerPolicies();
  15. Auth::provider('custom', function ($app, array $config) {
  16. // Return an instance of Illuminate\Contracts\Auth\UserProvider...
  17. return new CustomUserProvider();
  18. });
  19. }
  20. }

最后修改一下配置,打开config/admin.php,找到auth部分修改:

  1. 'auth' => [
  2. 'guards' => [
  3. 'admin' => [
  4. 'driver' => 'session',
  5. 'provider' => 'admin',
  6. ]
  7. ],
  8. // 修改下面
  9. 'providers' => [
  10. 'admin' => [
  11. 'driver' => 'custom',
  12. ]
  13. ],
  14. ],

这样就完成了自定义登陆认证的逻辑,自定义登陆算是laravel中比较复杂的部分,需要开发者有耐心的一步步调试完成。