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

Laravel 11.x Web用LDAP认证、API基础认证失效问题排查

问题原因分析
  1. 默认Guard与中间件不匹配:你的默认Guard是web,调用auth.basic中间件时会默认使用web guard的LDAP provider。LDAP的session驱动适配Web端有状态会话,认证失败后会重定向到Web登录页,但API路由无该页面,因此返回404。
  2. API Guard驱动选型错误:当前api guard使用session驱动,这是为Web端会话设计的,API请求为无状态模式,依赖session会导致认证失效并触发无效重定向。
解决方案一:Web用LDAP认证,API用Eloquent基础认证

1. 调整API Guard配置

修改config/auth.php中api guard的驱动为basic,适配无状态基础认证:

'api' => [
    'driver' => 'basic',
    'provider' => 'users',
],

2. 指定路由认证Guard

修改API路由的中间件,明确使用api guard进行基础认证:

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth.basic:api');

3. 确认Eloquent模型状态

确保App\Models\User模型包含password字段,且密码为Laravel加密格式(基础认证会验证密码哈希)。

解决方案二:Web和API均使用LDAP认证

1. 调整API Guard配置

修改config/auth.php中api guard关联LDAP provider,并使用basic驱动:

'api' => [
    'driver' => 'basic',
    'provider' => 'ldap',
],

2. 指定路由认证Guard

修改API路由中间件,使用api guard完成LDAP基础认证:

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth.basic:api');

3. 确认LDAP同步配置

确保LDAP配置中的数据库同步功能正常(已在你的配置中开启),认证时会自动将LDAP用户同步到本地数据库,返回同步后的用户模型。

额外优化:避免认证失败返回404

修改app/Exceptions/Handler.php(Laravel 11.x可在bootstrap/app.php中配置异常处理),让API认证失败时返回JSON格式的401响应,而非重定向:

use Illuminate\Auth\AuthenticationException;

// 在异常处理类中添加或修改unauthenticated方法
protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['message' => '认证失败'], 401);
    }

    return redirect()->guest(route('login'));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 06:25:54