在 Laravel 中使用 LDAP 身份验证的示例如下:

首先,安装 Laravel 的 LDAP 扩展包:

composer require adldap2/adldap2-laravel
  • 1.

然后,在 config/app.php 中注册服务提供程序:

'providers' => [
    // ...
    Adldap\Laravel\AdldapServiceProvider::class,
],
  • 1.
  • 2.
  • 3.
  • 4.

接下来,生成 LDAP 配置文件:

php artisan vendor:publish --provider="Adldap\Laravel\AdldapServiceProvider"
  • 1.

这将在 config/adldap.php 中生成 LDAP 配置文件。根据您的 LDAP 服务器环境,修改相应的配置项。

然后,创建一个 LDAP 认证驱动:

// app/Auth/LdapAuthProvider.php
namespace App\Auth;

use Adldap\Laravel\Facades\Adldap;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider;

class LdapAuthProvider implements UserProvider
{
    public function retrieveByCredentials(array $credentials)
    {
        $user = Adldap::search()->users()->find($credentials['username']);

        return $user;
    }

    public function validateCredentials(Authenticatable $user, array $credentials)
    {
        return Adldap::auth()->attempt(
            $credentials['username'],
            $credentials['password']
        );
    }

    // 其他需要实现的方法...
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

config/auth.php 中配置 LDAP 认证驱动:

'providers' => [
    'users' => [
        'driver' => 'ldap',
        'model' => App\Auth\LdapAuthProvider::class,
    ],
],
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

最后,在您的登录控制器中使用 LDAP 认证:

// app/Http/Controllers/Auth/LoginController.php
namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    public function login(Request $request)
    {
        $this->validateLogin($request);

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        return $this->sendFailedLoginResponse($request);
    }

    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.

这个示例演示了如何在 Laravel 中集成 LDAP 身份验证。